我有一个列表:
listvalue = ['charity','hospital','carrefour']
我试图从列表中合并两个索引:
twoconcat = [listvalue[i:i + 2] for i in range(len(listvalue))]
我得到的输出是:
[['charity', 'hospital'], ['hospital', 'carrefour'], ['carrefour']]`
我希望输出为
[['charity','hospital'],['charity','carrefour'],['hospital','charity'],['hospital','carrefour'],['carrefour','charity'],['carrefour','hospital']]
有什么建议吗?
答案 0 :(得分:2)
您可以使用itertools.permutations
进行此操作。
>>> places = ['charity','hospital','carrefour']
>>> list(itertools.permutations(places, 2))
[('charity', 'hospital'), ('charity', 'carrefour'), ('hospital', 'charity'),
('hospital', 'carrefour'), ('carrefour', 'charity'), ('carrefour', 'hospital')]
答案 1 :(得分:0)
如果您不关心列表理解。这会有所帮助, 在python 2.x上运行
listvalue = ['charity','hospital','carrefour']
arr_len= len(listvalue)
result=[]
for i in range(arr_len):
for j in range(arr_len):
if i !=j:
result.append([listvalue[i],listvalue[j]])
print result
[['charity', 'hospital'], ['charity', 'carrefour'], ['hospital', 'charity'], ['hospital', 'carrefour'], ['carrefour', 'charity'], ['carrefour', 'hospital']]
答案 2 :(得分:0)
l = ['a', 'b', 'c']
[[x, y] for x in l for y in l if y != x]
输出:
[['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']]
答案 3 :(得分:0)
@Alasdair是正确的...使用itertools。
代码:
from itertools import permutations
places = ['charity','hospital','carrefour']
result = list(permutations(places, 2)
输出:
[('charity', 'hospital'), ('charity', 'carrefour'), ('hospital', 'charity'), ('hospital', 'carrefour'), ('carrefour', 'charity'), ('carrefour', 'hospital')]
代码:
from itertools import permutations
places = ['charity','hospital','carrefour']
result = [list(place) for place in list(permutations(places, 2))]
输出:
[['charity','hospital'],['charity','carrefour'],['hospital','charity'],['hospital','carrefour'],['carrefour','charity'],['carrefour','hospital']]