Home > other >  Lists in lists and for loops
Lists in lists and for loops

Time:11-26

If I have lists with x lists and rows x and columns x for example

[[(1,2),(1,4)],[(7,5),(5,4)]]

How do I get another list that takes the first numbers of all the tuples in the lists and puts them in a list, and then takes the second numbers of all the tuples in the lists and puts them in a second list.how should I get that with 3 for loop

Expected output for the sample:

[(1,1),(7,5)],[(2,4),(5,4)]

CodePudding user response:

L = [[(1,2),(1,4)],[(7,5),(5,4)]]

result = list()
fIndexesList = list() #first items
sIndexesList = list() #second items

for item in L:
   
    fIndexesTuple = list()
    sIndexesTuple = list()
   
    for innerItem in item:
     fIndexesTuple.append(innerItem[0])
     sIndexesTuple.append(innerItem[1])
        
    else:     
     fIndexesList.append(tuple(fIndexesTuple))      
     sIndexesList.append(tuple(sIndexesTuple))
        
else:
    result.append(fIndexesList)
    result.append(sIndexesList)
print(result)

This should work By the way ,You can use the loop inside a function

CodePudding user response:

You could try to use zip:

numbers = [[(1, 2), (1, 4)], [(7, 5), (5, 4)]]
result = [list(tuples) for tuples in zip(*(zip(*tuples) for tuples in numbers))]

Result:

[[(1, 1), (7, 5)], [(2, 4), (5, 4)]]

CodePudding user response:

This should work


your_list = [[(1,2),(1,4)],[(7,5),(5,4)]]
new_list = []
first_temp_list = []
second_temp_list = []
for list_ in your_list:
    
    first_temp_list.append((list_[0][0],list_[1][0]))
    second_temp_list.append((list_[0][1],list_[1][1]))
        
new_list.append(first_temp_list)      
new_list.append(second_temp_list)      

print(new_list)

  • Related