我有多个列表。我想在每个列表的项目上运行for循环
foo = ["today", "tomorrow", "yesterday"]
bar = ["What", "is", "chocolate"]
empty = []
for x in [foo, bar]:
empty.append("mushroom" + x)
Runtime error
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'list' objects
foo = ["today", "tomorrow", "yesterday"]
bar = ["What", "is", "chocolate"]
def shroom(x):
print("mushroom" + x)
map(shroom, bar, foo)
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: shroom() takes exactly 1 argument (2 given)
我想要的输出是两个新变量,每个列表中的每个元素都有&#34;蘑菇&#34;附上。
fooMushroom = [mushroomtoday, mushroomtomorrow, mushroomyesterday]
fooBar = [mushroomWhat,mushroomis,mushroomchocolate]
即,我不希望每个列表中的每个元素都通过zip或类似函数进行配对。我需要将foo和bar的输出单独保存在变量中,而不是合并/配对。
答案 0 :(得分:0)
您可以简单地连接您的列表:
for x in foo + bar:
empty.append("mushroom" + x)
我没有看到你想要的输出。为清晰起见,您可以使用词典。
orig_data = {
"foo": ["a", "b", "c"],
"bar": ["a", "b", "c"]
}
mushroom_data = {}
for k,v in orig_data.iteritems():
for x in v:
if k not in mushroom_data:
mushroom_data[k] = []
mushroom_data[k].append("mushroom" + x)
print mushroom_data
最好的问候。
答案 1 :(得分:-1)
我知道你说你不想使用zip,但是通过这种方式你可以将每个元素都放在自己的变量中,这是你想要的吗?
fooMushroom = []
barMushroom = []
for x, y in zip(foo, bar):
fooMushroom.append("mushroom"+x)
barMushroom.append("mushroom"+y)