简体   繁体   English

Python-对于每个for循环迭代,追加到其他列表中

[英]Python- for each for loop iteration, append into a different list

I have a for loop that is taking data and appending it into a list, but for each iteration of the for loop, I would like it to append into a different list. 我有一个for循环,用于获取数据并将其追加到列表中,但是对于for循环的每次迭代,我希望将其追加到另一个列表中。 Is there any way to do this? 有什么办法吗?

    value = []
    for i in list:
        value.append(i)

but I would like something such as 但我想要这样的东西

    for i, num in enumerate(list):
        value_i.append(num)

How could I go about doing this? 我该怎么做呢?

Not lists, but close: 未列出,但关闭:

>>> zip([1, 2, 5])
[(1,), (2,), (5,)]
>>> lst = [1,2,3,4]
>>> [list(x) for x in zip(lst)]
[[1], [2], [3], [4]]

Btw, you should not use list as the variable name. 顺便说一句,您不应该使用list作为变量名。

Why not simply: 为什么不简单地:

>>> [ [e] for e in [1, 2, 3] ]
[[1], [2], [3]]

Supposing you already have a collection of lists 假设您已经有一个列表集合

my_lists = [list1, list2, list3, …, listN]

and a source list 和来源清单

my_sources = [val1, val2, val3, …, valN]

what you want is 你想要的是

for lst, src in zip(my_lists, my_sources):
    lst.append(src)

You could also do this by index: 您也可以按索引执行此操作:

for i in range(len(lst)):
    my_lists[i].append(my_sources[i])

The latter may seem less Pythonic, but it's pretty readable and probably more efficient than the zip approach. 后者似乎不像Python那样,但是它比zip方法更易读并且可能更有效。

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

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