【问题标题】:Updating List by using for loop使用 for 循环更新列表
【发布时间】:2015-12-22 21:04:46
【问题描述】:

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

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']

【问题讨论】:

  • 能否请您清理问题格式中的混乱并给变量一个正确的名称/正确的python语法?
  • 您能否也清楚地解释一下您想要得到的结果。
  • 如果您编写 cmets 来解释每个变量的含义,而不是在变量名中解释,那将会很有帮助。
  • 您确定List to be update 是列表列表吗?
  • 不幸的是..我从文件中随机选择元素并附加到列表中..结果是列表列表..

标签: python file loops for-loop


【解决方案1】:

好的,按照您评论中给出的示例进行操作

[1,2,3,4] 是我们的 L2 和 ETPL=[3,5,4,9,8,9,7] 第一个是高度 偏好和最后一个是最不偏好的元素..所以更新 列表将是= [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']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2021-07-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多