簡體   English   中英

如何比較列表中的項目?

[英]How to compare items in list?

這是我的清單

my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]

我的目標是排序或創建這樣的新列表

list1 = [18, 19, 20]
list2 = [27, 28, 29]
list3 = [38, 39, 40]

然后比較它們中的每一個,只留下這樣相等的項目,

list1 x == list2 x - 10 or list1 x == list3 x - 10
list1 x == list2 x + 10 or list1 x == list3 x + 10
list2 x == list1 x - 10 or list2 x == list3 x - 10
list2 x == list1 x + 10 or list2 x == list2 x + 10
list3 x == list1 x - 10 or list3 x == list2 x - 10
list3 x == list1 x + 10 or list3 x == list2 x + 10

所以最終的名單會像

final = [18,19,28,29,38,39]

我已經編寫了這些代碼,但無法實現目標。 那些只是不成功的嘗試。

N1

for lst in my_list:
    ind = my_list.index(lst)
    if int(my_list[ind]) == any(int(x)-10 for x in my_list) or int(my_list[ind]) == any(int(x)+10 for x in my_list):
        print(ind)

N2

for id in my_list:
    ind = my_list.index(id)
    try:
        if id == (my_list[ind+1])-1 and id :
            print(id)
    except IndexError:
            print("out of", id)

先感謝您。

聽起來您想將一個列表作為輸入並生成一個新列表,該列表僅包含與原始元素中的另一個元素相距 10 的原始元素。

my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
new_list = list(filter(lambda x: x + 10 in my_list or x - 10 in my_list, my_list))

這是使用python的filter方法的一種簡單方法。

結果:

[18, 19, 28, 29, 38, 39]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM