我有一行代码如下:
list1=[string1[i:i+int1] for i in range(0, len(string1), int1)]
我记得我的老师说我们应该在'for'时开始换行 那么,有没有办法编写看起来像这样的代码:
for i in range(0, len(string1), int1):
#something here
或其他什么?
答案 0 :(得分:5)
您的意思是从for loop
list-comprehension
list1=[string1[i:i+int1] for i in range(0, len(string1), int1)]
变为:
list1 = list()
for i in range(0, len(string1), int1):
list1.append(string1[i:i+int1])
如果您想在迭代数据时添加异常处理,日志记录或更复杂的函数或行为,这将非常有用。
例如:
list1 = list()
for i in range(0, len(string1), int1):
log.info('in loop: i={}'.format(i))
try:
data = string1[i:i+int1]
except:
log.error('oh no!')
# maybe do something complex here to get some data anyway?
data = complex_function(i)
log.debug('appending to list: data={}'.format(data))
list1.append(data)
但总的来说,列表理解是一种完全合法的写作方式。
答案 1 :(得分:3)
您必须先创建空列表,然后为每次迭代添加。
list1 = []
for i in range(0, len(string1), int1):
list1.append(string1[i:i+int1])
答案 2 :(得分:1)
该列表理解将转化为:
l = []
for i in range(0, len(string1), int1):
l.append(string1[i:i+int1])
答案 3 :(得分:0)
有点脏,但是将收集拆分为固定大小的子集合是一个很好的选择。
from itertools import zip_longest
l = []
for chunk in zip_longest(*([iter(string1)]*int1), fillvalue=''):
l.append(''.join(chunk))
答案 4 :(得分:0)
g = (string[i:i+int1] for i,char in enumerate(string) if i % int1 == 0)
l = list(g)
Do not use len(iterable)
in the while dealing with indices. Use enumerate()
for that. It yields (index, item)
. This is efficient and pythonic.
The idea that you should make a newline while using for
loop is probably idiomatic to some other language, C, C++ e.g. But not in python. List comprehensions come fro the Haskell world of FP. So that's elegant as they come.