简体   繁体   English

我该如何使用列表理解功能?

[英]How can i do this using list comprehension?

a='abcdcdc'
list_=[x*3 for x in a]
print list_

This is printing this OK!!!! 这正在打印此行!!!! :

['aaa', 'bbb', 'ccc', 'ddd', 'ccc', 'ddd', 'ccc']

But How can i print this ? 但是我该如何打印呢? :

['abc','cdc','cdc']

You can use: 您可以使用:

>>> [a[i:i+3] for i in range(0,len(a) - 1,2)]
['abc', 'cdc', 'cdc']

This means i will get the following values: 这意味着i将获得以下值:

>>> list(range(0,len(a) - 1,2))
[0, 2, 4]

(as the list comprehension loops over i ). (因为列表理解遍历i )。 This means that range(0,len(a) - 1,2) starts at 0 and in increments of 2 it'll increase until it reaches the highest value but no more than len(a) - 1 . 这意味着range(0,len(a) - 1,2)0开始,以2增量递增,直到达到最大值,但不超过len(a) - 1 There is a longer explanation in the Python 3 documentation about range() which can be helpful to read. Python 3文档中有关于range()的较长解释,这对阅读很有帮助。

This means it'll slice a into the desired segments (the notation a[i:j] means it'll take the slice from i to j of a ). 这意味着它会切片a成所需的分段(记号a[i:j]装置,它会采取的切片从ija )。 It'll first take the slice a[0:0 + 3] , then the slice a[2:2 + 3] and lastly the slice a[4:4 + 3] which are the strings that you're looking for. 首先要获取切片a[0:0 + 3] ,然后获取切片a[2:2 + 3] ,最后获取切片a[4:4 + 3] ,它们是您要查找的字符串。

We're subtracting 1 from the length of a as otherwise we don't end up with the result that we want: 我们从长度减去1 a否则我们不与我们想要的结果结束了:

>>> [a[i:i+3] for i in range(0,len(a),2)]
['abc', 'cdc', 'cdc', 'c']
[a[i]+a[i+1]+a[i+2] for i in range(0,len(a)-1,2)]

Using list comprehension here might actually be counter to the zen of Python ("simple is better than complex"). 在这里使用list comprehension实际上可能与Python禅宗相反(“简单胜于复杂”)。

Though the other list comprehensions answers are correct, it takes a while to understand why they work. 尽管其他列表理解答案是正确的,但仍需要一段时间才能理解它们的工作原理。

On the other hand, a code like the following isn't hard to figure out at first glance: 另一方面,乍一看,很难找到如下代码:

a='abcdcdc'

for i in range(0, len(a), 2):
    b = a[i:i+3]
    if len(b) == 3:
        print(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM