我正在尝试从列表中建立一个名字,姓氏组合。但是无法在我的循环函数中执行此操作。感谢一些帮助。
names = ['Appleby', 'James']
nn = ['James', 'Jim', 'Jimmy', 'Jimmie', 'Jamie', 'Jem']
combos = []
for g in nn:
names[1] = g
combos.append(names)
print(combos)
结果 :
[['Appleby', 'Jem'],
['Appleby', 'Jem'],
['Appleby', 'Jem'],
['Appleby', 'Jem'],
['Appleby', 'Jem'],
['Appleby', 'Jem']]
我想实现的是:
[['Appleby', 'James'],
['Appleby', 'Jim'],
['Appleby', 'Jimmy'],
['Appleby', 'Jimmie'],
['Appleby', 'Jamie'],
['Appleby', 'Jem']]
最佳答案
我相信您正在寻找两个列表中名称的所有组合。
您可以为此使用-
combos = [[name, n] for n in nn for name in names]
如果您只想与“ Appleby”组合。使用
combos = [[names[0], n] for n in nn]
问题是当您更新名称[1] = g时。它正在更新要在组合中多次添加的同一列表。有关更多信息,请检查python中的可变对象和不可变对象。
有关列表
+=
运算符的特定信息,请参见this answer。关于python - 使用Python循环生成列表组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58586175/