简体   繁体   English

从列表列表创建许多列表

[英]creating many lists from list of lists

i have created a list of lists through list comprehension and would like to unravel this list of lists into many lists through iteration (with the variable name of each list iterating aswell), is that possible? 我已经通过列表理解创建了一个列表列表,并希望通过迭代将该列表列表分解为许多列表(每个列表的变量名称也会迭代),这可能吗? as to what exactly i mean by that i want: 关于我想要的确切含义:

listoflists = [[1,2,3],[2,3,4],[3,4,5,6,7],["a","b"]]

with the output being: 输出为:

list1=[1,2,3]
list2=[2,3,4]
list3=[3,4,5,6,7]
list4=["a","b"]

so i not only get the unraveled lists but also the names of each list iterating with range(len(listoflists)). 所以我不仅获得了拆散的列表,而且还获得了使用range(len(listoflists))迭代的每个列表的名称。

For clarification as to why i need this, for my project i want to write a csv file with each column containing one of those lists. 为了澄清为什么我需要这样做,对于我的项目,我想编写一个csv文件,每一列都包含这些列表之一。

Consider forming a dictionary, where your separate lists are captured in the key-value pairs: 考虑组成一个词典,在键值对中捕获单独的列表:

>>> manylists = {f'list{i}': j for i, j in enumerate(listoflists, 1)}
>>> manylists
{'list1': [1, 2, 3], 'list2': [2, 3, 4],
 'list3': [3, 4, 5, 6, 7], 'list4': ['a', 'b']}

This roughly mimics the "dynamic variable creation" that you are trying to do, but instead of all of those lists floating around in your local namespace, they are all wrapped up in one neat data structure (a dictionary), called manylists . 这大致模拟了您尝试执行的“动态变量创建”,但是并不是所有这些列表都在本地名称空间中浮动,而是将它们全部包装在一个名为manylists简洁数据结构(字典)中。

You can also use simply dict(enumerate(listoflists, 1)) , where the resulting keys will be ints starting at 1 and ascending from there. 您还可以简单地使用dict(enumerate(listoflists, 1)) ,其中生成的键将是从1开始并从此处升序的整数。

You can iterate in your list of list with a simple for 您可以使用简单的

for list in listoflists:

And then print it in the format you want. 然后以所需的格式打印。

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

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