【问题标题】:python efficient way to compare item in list of tuplespython比较元组列表中项目的有效方法
【发布时间】:2022-07-22 20:00:28
【问题描述】:

是否有一种不使用 for 循环的有效方法来比较元组列表中的项目是否在 Python 中的所有元组中都相同?


lst_tups = [('Hello', 1, 'Name:'), ('Goodbye', 1, 'Surname:'), ('See you!', 1, 'Time:')]


预期的输出是返回元组索引 1 中项目的所有唯一值


unique = list()

for i in lst_tups:
    item = i[1]
    unique.append(item)


set(unique)
    

【问题讨论】:

  • 请添加预期的输出?

标签: python data-structures


【解决方案1】:

您可以使用chain.from_iterable 和三步切片:[::3]

from itertools import chain
res = list(chain.from_iterable(lst_tups))[::3]
print(res)

['Hello', 'Goodbye', 'See you!']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多