3 回答

TA貢獻1840條經(jīng)驗 獲得超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,然后不會觸發(fā)您的附加邏輯,從而傳遞該元素。

TA貢獻1785條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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)
添加回答
舉報