简体   繁体   English

如何自动从另一个列表的元素中创建 python 中的列表

[英]How to automate to make lists in python from the elements of another List

I have a list X of n number of elements, so I want to generate a list of each element from the list X.我有一个包含 n 个元素的列表 X,所以我想从列表 X 中生成每个元素的列表。

X = [ Task_1 , Task_2 , ... ]
for ele in X:
    ele = []

Now, if I use the following code, It gives me an error.现在,如果我使用以下代码,它会给我一个错误。

print(len(Task_1))
Output:
Task_1 is not defined

Use a dictionary instead:改用字典:

X = ['Task_1', 'Task_2', 'Task_3']

container = dict()
for item in X:
    container[item] = list()

Afterwards, you'll have eg之后,您将拥有例如

container["Task_1"]

as a list.作为一个列表。 The other way would involve globals()[item] = list() in the loop but this really messes up your namespace.另一种方式将涉及循环中的globals()[item] = list()但这确实会弄乱您的命名空间。

Although I do not recommend this, but you can:虽然我不推荐这个,但是你可以:

X = ['Task_1', 'Task_2', 'Task_3']

for item in X:
    globals()[item] = []
    
print(Task_1)
print(len(Task_1))

print(Task_2)
print(len(Task_2))

You can make a nested list, or dictionary instead.您可以创建一个嵌套列表或字典。

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

相关问题 Python-用另一个列表中的唯一元素替换列表中的重复元素 - Python - Replacing repeating elements in a list with unique elements from another lists 生成一个列表的列表,其元素来自另一个列表(Python) - Generating a list of lists whose elements come from another list (Python) 如何将元素列表与 Python 中的另一个列表列表相乘 - How do I multiply a list of elements with another list of lists in Python 如何使用Python中原始列表中的位置特定元素创建列表? - How to make a list of lists using position specific elements from original list in Python? 如何制作两个列表并根据另一个列表删除元素? - how to make take two lists and remove elements based on another list? 如何在python 3中将列表中的数字分配给另一个列表中的数字? - How to assign a number from a list of lists to another list of lists in python 3? 如何从现有列表列表中创建第一个元素的新列表 - How to make a new list of first elements from existing list of lists Python从列表列表中创建列表列表 - Python make a list of lists from a list of lists 使用另一个列表的元素过滤列表 - Python - Filtering lists with elements of another list - Python 检查列表列表的所有元素是否在另一个列表列表Python中 - Checking if all elements of a List of Lists are in another List of Lists Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM