我不确定如何从列表'meeps'和列表'peeps'中获得第一个单词。这是我迄今为止通过列表推导得到的代码。
meeps = ["Foghorn Leghorn", "Elmer Fudd", "Road Runner", "Bugs Bunny", "Daffy Duck", "Tasmanian Devil"]
peeps = ["John Cleese", "Michael Palin", "Terry Gilliam", "Terry Jones", "Graham Chapman","Eric Idle"]
mashemup1 = [(x.split()[0], y.split()[1]) for x in meeps for y in peeps]
print(mashemup1)
它像这样打印列表:
[('Foghorn', 'Cleese'), ('Foghorn', 'Palin'), ('Foghorn', 'Gilliam'), ('Foghorn', 'Jones'), ('Foghorn', 'Chapman'), ('Foghorn', 'Idle'), ('Elmer', 'Cleese'), ('Elmer', 'Palin'), ('Elmer', 'Gilliam'), ('Elmer', 'Jones'), ('Elmer', 'Chapman'), ('Elmer', 'Idle'), ('Road', 'Cleese'), ('Road', 'Palin'), ('Road', 'Gilliam'), ('Road', 'Jones'), ('Road', 'Chapman'), ('Road', 'Idle'), ('Bugs', 'Cleese'), ('Bugs', 'Palin'), ('Bugs', 'Gilliam'), ('Bugs', 'Jones'), ('Bugs', 'Chapman'), ('Bugs', 'Idle'), ('Daffy', 'Cleese'), ('Daffy', 'Palin'), ('Daffy', 'Gilliam'), ('Daffy', 'Jones'), ('Daffy', 'Chapman'), ('Daffy', 'Idle'), ('Tasmanian', 'Cleese'), ('Tasmanian', 'Palin'), ('Tasmanian', 'Gilliam'), ('Tasmanian', 'Jones'), ('Tasmanian', 'Chapman'), ('Tasmanian', 'Idle')]
可以使用zip并行处理两个列表。Zip将在两个列表中较短的列表处停止迭代。
mashemup = [x.split()[0] + ' ' + y.split()[1] for x, y in zip(meeps, peeps)]
print(mashempup)
['Foghorn Cleese', 'Elmer Palin', 'Road Gilliam', 'Bugs Jones', 'Daffy Chapman', 'Tasmanian Idle']
或者如果你需要一个元组列表:
mashemup = [(x.split()[0], y.split()[1]) for x, y in zip(meeps, peeps)]
print(mashempup)
[('Foghorn', 'Cleese'), ('Elmer', 'Palin'), ('Road', 'Gilliam'), ('Bugs', 'Jones'), ('Daffy', 'Chapman'), ('Tasmanian', 'Idle')]