2017-10-18 94 views
0

我想用Python 3來使用list_one對list_two進行排序並輸出到list_sorted。如果字段的值丟失,那麼我希望看到一個空值。輸出將具有相同數量的項目作爲list_one使用一個列表來排序另一個

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
list_two = ['seven', 'five', 'four', 'three', 'one'] 
list_sorted = [] 

for i in list_one: 
    for field in list_two: 
     if i == field: 
      list_sorted.append(field) 
     else: 
      list_sorted.append(None) 

print ('final output:', list_sorted) 

所需的輸出是:

['one', None, 'three', 'four', 'five', None, 'seven'] 

但它的實際輸出:

[None, None, None, None, 'one', None, None, None, None, None, None, None, None, 'three', None, None, None, 'four', None, None, None, 'five', None, None, None, None, None, None, None, None, 'seven', None, None, None, None] 

我現在的想法是答案涉及enumerate但我不確定。任何幫助將大大讚賞。

+0

看起來並不像你正在排序的東西。 –

回答

1

list_two轉換成一個集合,然後根據該元素是否在list_two建立一個列表理解。

set_two = set(list_two) 
list_sorted = [x if x in set_two else None for x in list_one] 

print(list_sorted) 
['one', None, 'three', 'four', 'five', None, 'seven'] 
+0

太棒了!謝謝@coldspeed。我有一些閱讀要做。我不知道這是否適合StackOverflow,但我還有兩個問題:是他們稱之爲「三元」還是速記?如果是這樣,什麼是長期版本?我不明白那裏發生了什麼。第二個問題是,如果list_two是二維的呢? – Jarvis

+0

@Jarvis不,這被稱爲「列表理解」。三元或簡寫是一個不同的概念,涉及在單行中級聯if-else語句(您在此看不到)。至於你的第二個問題,解決方案是相似的,你只需要將維度擴展爲1.如果你想知道如何做到這一點,請提出一個新問題。此外,您可以標記接受的最有幫助的答案,所以請考慮這樣做。謝謝。 –

1

你不是真的排序任何東西,但它看起來像你可以達到你想要一部測試i是否存在於list_two。刪除內部for循環。

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
list_two = ['seven', 'five', 'four', 'three', 'one'] 
list_sorted = [] 

for i in list_one: 
    if i in list_two: 
     list_sorted.append(i) 
    else: 
     list_sorted.append(None) 

print ('final output:', list_sorted) 
+0

更好地轉換爲一組快速查找! https://stackoverflow.com/a/46801255/4909087 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ看起來很短,這絕對看起來不錯,但它真的更快?我在'list_one'中看到一個'for x',如果x在set_two else None中看到'x,這看起來與我所得到的非常相似。但是我沒有寫太多的Python - 是最Pythonista的方式嗎? –

+1

重要的位是'x if x in set_two else None',這有利於查找,因爲集合可以支持O(1)中的查找,而列表(例如list_two)則不能。小列表中看不出這種差異,但這種方法在複雜度上是二次的。仍然,很好的努力,所以你有我的投票:) –