对多个列表中的元素使用forloop

2024-06-26 01:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多张单子。我想对每个列表的项运行for循环

尝试1

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

尝试2

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)

我想要的输出是两个新变量,其中每个列表中的每个元素都附加了“蘑菇”

fooMushroom = [mushroomtoday, mushroomtomorrow, mushroomyesterday]
fooBar = [mushroomWhat,mushroomis,mushroomchocolate]

注意:我不想使用拉链对

也就是说,我不希望每个列表中的每个元素通过zip或类似函数成对出现。我需要foo和bar的输出分别保存在一个变量中,而不是合并/配对


Tags: in列表fortodayfooisbarwhat
2条回答

您可以简单地连接列表:

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

致以最诚挚的问候

我知道你说过你不想使用zip,但是这样你就可以让每个元素都有自己的变量,这就是你想要的吗

fooMushroom = []
barMushroom = []
for x, y in zip(foo, bar):
    fooMushroom.append("mushroom"+x)
    barMushroom.append("mushroom"+y)

相关问题 更多 >