【发布时间】: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
我是 Python 新手。 我有一个元组 元组=(3,4,5) 我有一个清单。 列表=[3,5]
我希望输出为 4,因为 [3,5] 存在于 (3,4,5) 中 如何使用 Python 做到这一点?
【问题讨论】:
标签: python list python-3.x tuples
您可以将您的可迭代对象转换为集合,然后执行集合差异。
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}
【讨论】:
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])
【讨论】: