简体   繁体   English

如何遍历元组列表并比较元素?

[英]how to iterate through a list of tuples and compare elements?

I have a list of tuples such as我有一个元组列表,例如

list_tuples = [(2,3), (4,7), (3,2), (7,8), (7,4)]

I want to find the tuples in this list whose elements are the same but reversed order.我想在这个列表中找到元素相同但顺序相反的元组。 in this case my output would be:在这种情况下,我的输出将是:

new_list_tuples = [(2,3), (3,2), (4,7), (7,4)]

I've tried the below code but apparently it doesn't work because it doesn't make sense:我已经尝试了下面的代码,但显然它不起作用,因为它没有意义:

for i in lista:
    if i[0] == i[1] and i[1] == i[0]:
        print(i)

can anyone help me with this?谁能帮我这个? Many thanks in advance!提前谢谢了!

You can use a list comprehension:您可以使用列表理解:

>>> [t for t in list_tuples if (t[1], t[0]) in list_tuples]
[(2, 3), (4, 7), (3, 2), (7, 4)]

That being said, using a set for lookups is faster :话虽如此,使用set进行查找更快

>>> set_tuples = set(list_tuples)
>>> [t for t in list_tuples if (t[1], t[0]) in set_tuples]
[(2, 3), (4, 7), (3, 2), (7, 4)]

What i can think of is you can use nested for loop我能想到的是你可以使用嵌套的 for 循环

new_list_tuple=[(2,3), (3,2), (4,7), (7,4)]
convert_list=[]
for i in range(len(new_list_tuple)):
    for j in range(i,len(new_list_tuple)):
        if new_list_tuple[i]==new_list_tuple[j][::-1]:
            convert_list.extend([new_list_tuple[i],new_list_tuple[j]])
print(convert_list)

Main idea is divide tuple into two section front number, and back number.主要思想是将元组分为前数和后数两部分。

If front_numbers[X] == Back_number[Y] and front_number[Y] == Back_number[X].如果 front_numbers[X] == Back_number[Y] 和 front_number[Y] == Back_number[X]。 It means list_tuples[X] and list_tuples[Y] have same element but opposite sequence.这意味着 list_tuples[X] 和 list_tuples[Y] 具有相同的元素但顺序相反。

list_tuples = [(2,3), (4,7), (3,2), (7,8), (7,4)]

front_number = []
back_number = []

for i in range(len(list_tuples)):
    front_number.append(list_tuples[i][0])
    back_number.append(list_tuples[i][1])

new_list_tuple = []

for i, v in enumerate(front_number):
    for b_i, b_v in enumerate(back_number):
        if b_i == i:
            pass
        elif v == b_v:
            if front_number[b_i] == back_number[i]:
                if (front_number[i], back_number[i]) not in new_list_tuple:
                    new_list_tuple.append((front_number[i],back_number[i]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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