[英]Leave parts of the instructions blank for python to complete
我是 Python 的新手,所以我不知道这是否可能,但我的猜测是肯定的。 我想遍历一个列表并根据它们的值将项目放入新列表中。 例如,如果item_x == 4
,我想把它放在一个名为list_for_4
的列表中。 我的列表中的所有其他项目和数字 0 到 10 也是如此。因此,是否可以以这样的方式概括一个语句,如果item_x == *a certain value*
,它将附加到list_for_*a certain value*
? 谢谢!
也许在内部使用带有 if 语句的列表理解?
喜欢:
list_for_4 = [x for x in my_list if x==4]
并将其与字典结合起来。
而不是试图生成一个动态变量。 使用字典结构的 map 可能会对您有所帮助。
例如:
from collections import defaultdict
item_list = [1, 2, 3, 9, 2, 2, 3, 4, 4]
# Use a dictionary which elements are a list by default:
items_map = defaultdict(list)
for i in item_list:
items_map['list_for_{}'.format(i)].append(i)
print(items_map)
# Test the map for elements in the list:
if 'list_for_4' in items_map:
print(items_map['list_for_4'])
else:
print('`list_for_4` not found.')
或者,如果您只需要一个项目在列表中出现的次数,您可以使用Counter聚合它:
from collections import Counter
item_list = [1, 2, 3, 9, 2, 2, 3, 4, 4]
result = Counter(item_list)
print(result)
通过列表的简单迭代:
lst_for_1 = []
lst_for_2 = []
lst_for_3 = []
d = {1: lst_for_1, 2: lst_for_2, 3: lst_for_3}
for x in lst:
d[x].append(x)
或者,如果您想要一个比 x 的值更复杂的条件,请定义一个 function:
def f(x):
if some condition...:
return lst_for_1
elif some other condition:
return lst_for_2
else:
return lst_for_3
然后将d[x].append(x)
替换为f(x).append(x)
。
如果您不想自己进行迭代,也可以使用 map:
list(map(lambda x: d[x].append(x),lst))
或者
list(map(lambda x: f(x).append(x),lst))
带有Nones
的版本将返回您不关心的 None 列表。 map(...)
返回一个迭代器,只要你不迭代它(例如,将其结果变成一个列表),它就不会执行映射。 这就是您需要list(map(...))
的原因,它会创建一个虚拟列表,但 append 将lst
的项目放在正确的列表中,这就是您想要的。
不知道你为什么要这样做。 但你可以做到。
data = [1, 2, 3, 4, 1, 2, 3, 5]
for item in data:
name = f'list_for_{item}'
if name in globals():
globals()[name].append(item)
else:
globals()[name] = [item]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.