【问题标题】:Checking if an element exists in a tuple and retrieving the other elements of tuple using Python检查元组中是否存在元素并使用 Python 检索元组的其他元素
【发布时间】:2017-08-02 00:46:37
【问题描述】:

我是 Python 新手。 我有一个元组 元组=(3,4,5) 我有一个清单。 列表=[3,5]

我希望输出为 4,因为 [3,5] 存在于 (3,4,5) 中 如何使用 Python 做到这一点?

【问题讨论】:

  • 使用集差操作?

标签: python list python-3.x tuples


【解决方案1】:

您可以将您的可迭代对象转换为集合,然后执行集合差异。

In [459]: t = (3,4,5) 

In [460]: l = [3,5]

In [461]: set(t) - set(l) if all(x in t for x in l) else None
Out[461]: {4}

【讨论】:

  • 这不排除元组中没有元素的列表。
  • @Prune 谢谢,很抱歉,不得不回应你。
  • 只要我们对档案有一个可靠的答案,我就很高兴。
【解决方案2】:
my_tuple = (3, 4, 5)
my_list = [3, 5]

# Check to see whether each item in your list is also in the tuple.    
if all(item in my_tuple for item in my_list):
    # Convert both to sets and print the difference.
    print set(my_tuple) - set(my_list)

输出:

set([4])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多