使用for循环更新列表

时间:2015-12-22 21:04:47

标签: python file loops for-loop

我有几个列表,我想更新它们。

L1=[["Turkey"],["Ireland"],["Ukraine"],["U.S.A"],["Greece"]]
L2=[["Flower"],["Dessert"],["Ice"],["Green"],["Purple"]]

我希望根据英雄的偏好更新列表..这样......

Element "Turkey's" Preference List(ETPL): ['Purple', 'Dessert', 'Red', 'Rouge', 'Blue', 'Mystique', 'Cold', 'Black', 'Fun', 'Storm']
Updated Preference List:[' Purple', 'Dessert', 'Blue', 'Fun', 'Storm']

如你所见,我正在尝试编码..但是我错了。我的代码到目前为止..

   common=[]
   for i in ETPL: # looks for the elements of turkey's preference list.
     for k in L1: # the list element which is a list.
        for b in k: 
            for z in b: # the element itself
                if i==z:
                    common.append(i)
   print(common)

L2和ETPL将在它们之间进行比较。 然后根据首选项列表对L2进行排序。

你能帮我解决一下吗?哪里错了?

预期输出为:

Updated Preference List:[' Purple', 'Dessert', 'Blue', 'Fun', 'Storm']

1 个答案:

答案 0 :(得分:0)

好的,按照评论中给出的示例

  

[1,2,3,4]是我们的L2和ETPL = [3,5,4,9,8,9,7]第一个是高度的   preferenced和last one是最不喜欢的元素..所以更新   列表将是= [3,4,1,2]

以下代码

L2 = [1,2,3,4]
ETPL = [3,5,4,9,8,9,7]
op = filter(lambda x: x not in ETPL, L2) # the unique original prefs
tp = filter(lambda x: x in ETPL, L2) # the well known prefs
L2 = sorted(tp, key=lambda x: ETPL.index(x)) # sort them according to their position
L2.extend(op) # add the unique original prefs
print(L2)

产生

[3, 4, 1, 2]

或者,使用

L2 = ['Flower', 'Dessert', 'Ice', 'Green', 'Purple']
ETPL = ['Purple', 'Dessert', 'Red', 'Rouge', 'Blue', 'Mystique', 'Cold', 'Black', 'Fun', 'Storm']

它产生

['Purple', 'Dessert', 'Flower', 'Ice', 'Green']

但是,如果您的数据与问题中描述的一样(即您有一个列表列表),则可以使用第一个元素来区分

L2 = [["Flower"],["Dessert"],["Ice"],["Green"],["Purple"]]
ETPL = ['Purple', 'Dessert', 'Red', 'Rouge', 'Blue', 'Mystique', 'Cold', 'Black', 'Fun', 'Storm']
op = filter(lambda x: x[0] not in ETPL, L2) # the unique original prefs
tp = filter(lambda x: x[0] in ETPL, L2) # the well known prefs
L2 = sorted(tp, key=lambda x: ETPL.index(x[0])) # sort them according to their position
L2.extend(op) # add the unique original prefs
print(L2)
制造

[['Purple'], ['Dessert'], ['Flower'], ['Ice'], ['Green']]