简体   繁体   中英

Python check if an item is in a nested list at a certain index

I generated a nested list of unique pairs, where each item exists in two pairs.

my_list = [['item1', 'item2'],
           ['item3', 'item4'],
           ['item5', 'item6'],
           ['item7', 'item8'],
           ['item1', 'item9'],
           ['item3', 'item10'],
           ['item5', 'item11'],
           ['item7', 'item12'],
           ['item13', 'item2'],
           ['item14', 'item4'],
           ['item15', 'item6'],
           ['item16', 'item8'],
           ['item13', 'item9'],
           ['item14', 'item10'],
           ['item15', 'item11'],
           ['item16', 'item12']]

But the requirement is that each item needs to exist at each index only once. So item1 for example should show up at index 0 of the sublist once and index 1 of the sublist the second time it shows up in a pair or vice versa.

I tried using any() with a conditional to check if the item exists in the nested list, but can't figure out how to check if it exists at an index in the sublist already, in which case I would reverse the nested list.

for pair in my_list:
    if any(item in sublist for sublist in my_list):
        pair.reverse()

I assume that you don't want to output the list if either 1st or last item in that list exist. I just added each indices into 2 different list and see if it exist and created an output. There must be a better pythonic solution.

new0=[]
new1=[]
for i in my_list:
    if i[0] not in new0 and i[1] not in new1:
        print(i)
        new0.append(i[0])
        new1.append(i[1])

The problem is that you don't have any "already" list to reference. You need to build that as you go. Here is an excruciatingly simple example solution:

# Keep separate lists for each position.
good_list_0 = []
good_list_1 = []

for pair in my_list:
    # If either element already exists at that index ...
    if pair[0] in good_list_0 or \
       pair[1] in good_list_1:

        # ... reverse the pair
        a, b = pair[1], pair[0]
    else:
        a, b = pair

    # add the values to the appropriate index lists
    good_list_0.append(a)
    good_list_1.append(b)

# Zip the two lists back together.
good_list = list(zip(good_list_0, good_list_1))

for pair in good_list:
    print(pair)

Output:

('item1', 'item2')
('item3', 'item4')
('item5', 'item6')
('item7', 'item8')
('item9', 'item1')
('item10', 'item3')
('item11', 'item5')
('item12', 'item7')
('item2', 'item13')
('item4', 'item14')
('item6', 'item15')
('item8', 'item16')
('item13', 'item9')
('item14', 'item10')
('item15', 'item11')
('item16', 'item12')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM