0

in PYTHON i have one list and i want to make from it a multiple lists, for every item i want him to create a list with the other items

my initial list :

cities = ['Chevalley', 'A.Gharmoul 1', 'El Madania']

then i want the output to be :

[
  ['Chevalley', 'A.Gharmoul 1'],
  ['Chevalley','El Madania'],
  ['A.Gharmoul 1', 'El Madania']
]

3

6 Answers 6

1

The below code will help you to create the resultant list you are looking for:

items = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
res = [[items[i],items[j]] for i in range(len(items)) for j in range(i+1, len(items))]
print(res)
Sign up to request clarification or add additional context in comments.

Comments

1
result_list = []
for i in ['Chevalley', 'A.Gharmoul 1', 'El Madania']:
    for j in ['Chevalley', 'A.Gharmoul 1', 'El Madania']:
        if i != j:
            result_list.append([i, j])

It should iterate over every possible pairing while ignoring pairing element with itself.

Comments

0

while this isn't the same it is pretty close to what you are looking for.

import itertools
a = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
result = list(itertools.combinations(a,2)) # number is the amount of items you want in the resultant tuple

result will have tuples of length 2 in a list.

Comments

0

Below should do it:

l  = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
n = [[l[i], l[j]] for i in range(0, len(l) - 1, 1) for j in range(i + 1, len(l), 1)]

n will equate to:

[['Chevalley', 'A.Gharmoul 1'],
 ['Chevalley', 'El Madania'],
 ['A.Gharmoul 1', 'El Madania']]

Comments

0

nested for loops does your work

list1 =['Chevalley', 'A.Gharmoul 1', 'El Madania']

output =[]

for i in range(len(list1)):
 for j in range(i+1,len(list1)):
  output.append([list1[i],list1[j]]) 

print(output)#[['Chevalley', 'A.Gharmoul 1'],['Chevalley','El Madania',['A.Gharmoul 1', 'El Madania']]

Comments

0

You can use itertools and convert the output tuples into lists:

import itertools

new = [ list(el) for el in itertools.combinations(['Chevalley', 'A.Gharmoul 1', 'El Madania'], 2) ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.