[英]print first element of tuple if any other element matches in python
I have a tuple in a list like 我在一个列表中有一个元组
A = [(2, 'two', '2nd', 'second')]
and I am getting a variable 'B' which is possibly rest of elements in the list 'A' except first element. 我得到一个变量“ B”,它可能是列表“ A”中除第一个元素之外的其余元素。
For example: 例如:
B = ['two'] # or ['2nd'], or ['second']
I want to print first element of tuple 'A' if the variable 'B' matches with tuple 'A' 如果变量“ B”与元组“ A”匹配,我想打印元组“ A”的第一个元素
I have tried 我努力了
[x for x,y,z,t in a[0] if b[0] == y or b[0] == z or b[0] == t ]
I am getting below error. 我正在错误以下。
TypeError: 'int' object is not iterable
TypeError:“ int”对象不可迭代
Please help. 请帮忙。
try this 尝试这个
li = []
for b in B:
li += [a[0] for a in A if b in a[1:]]
This will work for n number of items in A and m number of items in B. Final output will be the first element of tuples in the list A which have at least one value that matches any element of B 这将适用于A中的n个项目和B中的m个项目。最终输出将是列表A中元组的第一个元素,其元组至少具有一个与B的任何元素匹配的值
Hope this will solve your issue 希望这能解决您的问题
UPDATE 更新
Shorthand will be 速记将是
[a[0] for b in B for a in A if b in a[1:]]
Forgot to add in the first place. 忘了先添加。
Sample output 样品输出
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> A = [(2, 'two', '2nd', 'second'), (3, 'three', '3rd', 'third')]
>>> B = ['three']
>>> [a[0] for b in B for a in A if b in a[1:]]
[3]
>>>
>>>
>>> A = [(2, 'two', '2nd', 'second'), (3, 'three', '3rd', 'third')]
>>> B = ['two', '3rd']
>>> [a[0] for b in B for a in A if b in a[1:]]
[2, 3]
>>>
Try this single liner and use in
to check element exitance: - 试试这个单排和使用
in
检查元件出射度: -
A = [(2, 'two', '2nd', 'second')]
B = ['two']
print [i[0] for i in A if B[0] in i]
#[2]
B = ['two1']
print [i[0] for i in A if B[0] in i]
#[]
You're almost there -- you just need 您快要到了-您只需要
x for x,y,z,t in a
instead of 代替
x for x,y,z,t in a[0]
Why not 为什么不
A = [(2, 'two', '2nd', 'second')]
B = ['two']
if B[0] in A[0][1:]:
print A[0][0]
Do not use list comprehension if you want to print. 如果要打印,请不要使用列表推导。 Use simple for loop.
使用简单的for循环。
In [12]: A = [(2, 'two', '2nd', 'second')]
In [13]: B = ['two']
In [14]: for tup in A:
...: if B[0] in tup:
...: print(tup[0])
If you want final list try list comprehension. 如果您想要最终列表,请尝试理解列表。 You can index tuple.
您可以索引元组。 No need to unpack the entire tuple.
无需打开整个元组的包装。
In [15]: [tup[0]
...: for tup in A
...: if B[0] in tup]
Out[15]: [2]
for x,y,z,t in a[0] is equal to for x,y,zt,t in 2,for x,y,zt in 'tow',for x,y,z,t in '2nd'……,but the 2 is int which is not iterable.You can try other ways such as cut the first element of a[0] than judge if a[0] is equal to b[0]. a [0]中的x,y,z,t等于2中的x,y,zt,t等于'拖曳'中的x,y,zt,'2nd'中的x,y,z,t ……,但是2是不可迭代的int。您可以尝试其他方法,例如剪切a [0]的第一个元素,而不是判断a [0]是否等于b [0]。 Hold I can help you!
稍等,我可以帮助您!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.