3 回答
TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個贊
根據(jù)評論,您不想使用list comprehension,sort并且子列表中始終有 2 個元素,那么以下方法會有所幫助,
它遍歷列表并反轉(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個贊
一種方法是對它進(jìn)行排序,如果最終列表中不存在,則像 LogicalBranch 在答案中提到的那樣進(jìn)行追加。
你提到你不能使用sort并且2列表中總是有元素。然后,您可以通過制作另一個與列表相反的列表并在最終答案中進(jìn)行比較來做一個簡單的技巧。看下面的代碼
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個贊
實(shí)現(xiàn)此目的的最簡單方法(不導(dǎo)入任何內(nèi)容)是在將列表中的每一對添加到新結(jié)果列表之前對其進(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
然后你會像這樣使用它:
list_filter([[4, 1], [1, 4], [0, 5], [5, 0]])
這應(yīng)該返回一個如下所示的列表:
[[1, 4], [0, 5]]
編輯:沒有排序的更新方法:
(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
然后你會像這樣使用它:
new_filter_function([[4, 1], [1, 4], [0, 5], [5, 0]])
它還應(yīng)該返回一個如下所示的列表:
[[1, 4], [0, 5]]
祝你好運(yùn)。
添加回答
舉報(bào)
