【问题标题】:search list of tuples and exchange tup[0] for tup[2] in another list搜索元组列表并将 tup[0] 交换为另一个列表中的 tup[2]
【发布时间】:2014-11-17 22:38:32
【问题描述】:
x =  [(u'red', 3.5, u'rouge'), (u'green', 2.6, u'vert'), (u'blue', 1.45, u'blu')]

y = [('bue', 14.5), ('red', 140.0), ('green', 130.0), ('', 0.0)]

我想在 x 中搜索 y[0],如果找到,将 x[0] 更改为 y[0]。

当我尝试循环遍历元组时,我收到了 TypeError: list indices must be integers, not tuple。

对不起,我会再试一次。

x = [('a', 'b','c'),('d','e','f'),('g','h','i')]
y = [('zzz',10), ('xxx',20), ('yyy',30)]

我想最终得到一个y =[('c', 10),('f',20),('i',30)] 列表

我尝试了很多东西,但我是 python 新手,并尝试了以下方法

for tup  in x:
      results = [(tup[2]) for tup in x]

for tup in x:
    if tup[0] == y[tup[0]]:
        y[tup[0]] = tup[2]

【问题讨论】:

  • 你尝试了什么,显示代码??
  • 让我们看看你的代码。
  • 一个简单的d = {i[0]: i[2] for i in x} 然后[(d.get(i[0], i[0]), i[1]) for i in y] 应该怎么做?

标签: python list tuples list-comprehension


【解决方案1】:

这是对您问题的字面解释,如果 y[0][0] 即 'blue' 在 x 中的任何元组中,则将该元组交换为 y[0],我认为应该包含 blue 而不是 bue所以x[2] 变成了y[0]:

x = [(u'red', 3.5, u'rouge'), (u'green', 2.6, u'vert'), (u'blue', 1.45, u'blu')]

y = [('blue', 14.5), ('red', 140.0), ('green', 130.0), ('', 0.0)]

for ind, tup in enumerate(x):
    if y[0][0] in tup:
        x[ind] = y[0]
print(x)
[(u'red', 3.5, u'rouge'), (u'green', 2.6, u'vert'), ('blue', 14.5)]

或者使用列表推导并创建一个新列表:

print([y[0]  if tup[0] == y[0][0] else tup for tup in x])
[(u'red', 3.5, u'rouge'), (u'green', 2.6, u'vert'), ('blue', 14.5)]

只交换元素:

x = [('a', 'b','c'),('d','e','f'),('g','h','i')]
y = [('zzz',10), ('xxx',20), ('yyy',30)]


for ind,ele in enumerate(x):
    y[ind] = (ele[-1],y[ind][1])
print(y)
[('c', 10), ('f', 20), ('i', 30)]

【讨论】:

  • 我已经尝试过了,但它并没有达到我想要的效果,也许我在天真时解释错了。
  • x = [('a', 'b','c'),('d','e','f'),('g','h','i ')] y = [('zzz',10), ('xxx',20), ('yyy',30)] 我想得到一个等于 result = [('c', 10) 的列表, ('f',20),('i',30)]
  • 添加您的预期输出
  • y =[('c', 10),('f',20),('i',30)]
  • 你是明星!我非常感激。
猜你喜欢
  • 2019-02-15
  • 2015-06-18
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多