3 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
根據(jù)評(píng)論,您不想使用list comprehension,sort并且子列表中始終有 2 個(gè)元素,那么以下方法會(huì)有所幫助,
它遍歷列表并反轉(zhuǎn)子列表并檢查它們是否存在于 new_list
x = [[4, 1], [1, 4], [0, 5], [5, 0]]
new_list = []
for i in x:
if i[::-1] not in new_list and i not in new_list:
new_list.append(i)
print(new_list)
輸出:
[[4, 1], [0, 5]]

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
一種方法是對(duì)它進(jìn)行排序,如果最終列表中不存在,則像 LogicalBranch 在答案中提到的那樣進(jìn)行追加。
你提到你不能使用sort并且2列表中總是有元素。然后,您可以通過(guò)制作另一個(gè)與列表相反的列表并在最終答案中進(jìn)行比較來(lái)做一個(gè)簡(jiǎn)單的技巧??聪旅娴拇a
ans = []
l = [[4, 1], [1, 4], [0, 5], [5, 0]]
for x in l:
a = x[::-1]
if x not in ans and a not in ans:
ans.append(x)
print(ans) # [[4, 1], [0, 5]]

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
實(shí)現(xiàn)此目的的最簡(jiǎn)單方法(不導(dǎo)入任何內(nèi)容)是在將列表中的每一對(duì)添加到新結(jié)果列表之前對(duì)其進(jìn)行排序,如下所示:
result = []
for pair in [[4, 1], [1, 4], [0, 5], [5, 0]]:
pair.sort()
if pair not in result:
result.append(pair)
print(result)
您甚至可以將其轉(zhuǎn)換為函數(shù):
def list_filter(collection):
result = []
for pair in collection:
pair.sort()
if pair not in result:
result.append(pair)
return result
然后你會(huì)像這樣使用它:
list_filter([[4, 1], [1, 4], [0, 5], [5, 0]])
這應(yīng)該返回一個(gè)如下所示的列表:
[[1, 4], [0, 5]]
編輯:沒(méi)有排序的更新方法:
(result, collection) = ([], [[4, 1], [1, 4], [0, 5], [5, 0]])
def check(n1, n2):
for pair in collection:
if n1 in pair and n2 in pair and sorted(pair) in collection:
return True
return False
for pair in collection:
pair.sort()
if pair not in result:
result.append(pair)
print(result)
您甚至可以將其轉(zhuǎn)換為函數(shù):
def new_filter_function(collection):
result = []
def check(n1, n2):
for pair in collection:
if n1 in pair and n2 in pair and ([n1, n2] in collection or [n2, n1] in collection):
return True
return False
for pair in collection:
if pair not in result:
result.append(pair)
return result
然后你會(huì)像這樣使用它:
new_filter_function([[4, 1], [1, 4], [0, 5], [5, 0]])
它還應(yīng)該返回一個(gè)如下所示的列表:
[[1, 4], [0, 5]]
祝你好運(yùn)。
添加回答
舉報(bào)