Python - как объединить два индекса из списка - PullRequest
0 голосов
/ 26 июня 2018

У меня есть список:

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']]

Есть предложения?

Ответы [ 4 ]

0 голосов
/ 26 июня 2018

@ 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']]
0 голосов
/ 26 июня 2018

Вы можете сделать это, используя itertools.permutations.

>>> places = ['charity','hospital','carrefour']
>>> list(itertools.permutations(places, 2))
[('charity', 'hospital'), ('charity', 'carrefour'), ('hospital', 'charity'), 
('hospital', 'carrefour'), ('carrefour', 'charity'), ('carrefour', 'hospital')]
0 голосов
/ 26 июня 2018
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']]
0 голосов
/ 26 июня 2018

Если вас не волнует понимание списка. Это может быть полезно, работает на 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']]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...