3 回答
TA贡献1840条经验 获得超5个赞
# Separate lists of (name, is_in_image) tuples
>>> a = [('ELON_MUSK', True), ('BARACK_OBAMA', False), ('DONALD_TRUMP', False)]
>>> b = [('ELON_MUSK', False), ('BARACK_OBAMA', True), ('DONALD_TRUMP', False)]
# Combine the lists
>>> together = a + b
# Create a list containing all names if the second element (is_in_image) is True
>>> [name for name, is_in_image in together if is_in_image]
['ELON_MUSK', 'BARACK_OBAMA']
>>> print('People in this image: {}'.format(', '.join([name for name, is_in_image in together if is_in_image])))
People in this image: ELON_MUSK, BARACK_OBAMA
我认为你目前的做法主要的问题是,你的追加试验if 'True' in names_with_result,而不是if True in names_with_result... 'True' != True...
>>> sample_result = ('ELON_MUSK', True)
>>> 'True' in sample_result
False
>>> True in sample_result
True
第一个测试'True' in sample_result返回 False,然后不会触发您的附加逻辑,从而传递该元素。
TA贡献1785条经验 获得超8个赞
你也可以这样做:
l1 = [('ELON_MUSK', True), ('BARACK_OBAMA', False), ('DONALD_TRUMP', False)]
l2 = [('ELON_MUSK', False), ('BARACK_OBAMA', True), ('DONALD_TRUMP', False)]
# join the two list
l1.extend(l2)
# create a simple function that return a list of true
f = lambda x: [i for i,j in x if j]
print('{} is not {}'.format(*f(l1)))
TA贡献1895条经验 获得超7个赞
试试这个:
A= [('ELON_MUSK', True), ('BARACK_OBAMA', False), ('DONALD_TRUMP', False)]
B= [('ELON_MUSK', False), ('BARACK_OBAMA', True), ('DONALD_TRUMP', False)]
name_list = ''.join([a[0]+' , '+b[0] for a in A for b in B if a[1]==True and b[1]== True])
print("People in this image: "+ name_list)
添加回答
举报