我有2个清单:
my_values = ['0,78', '0,40', '0,67']
my_list = [
['Morocco', 'Meat', '190,00', '0,15'],
['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'],
['Morocco', 'Meat', '188,49', '0,78'],
['Morocco', 'Meat', '187,99', '0,101'],
['Spain', 'Meat', '190,76', '0,10'],
['Spain', 'Meat', '190,16', '0,20'],
['Spain', 'Meat', '189,56', '0,35'],
['Spain', 'Meat', '189,01', '0,40'],
['Spain', 'Meat', '188,13', '0,75'],
['Spain', 'Meat', '187,95', '0,78'],
['Italy', 'Meat', '190,20', '0,11'],
['Italy', 'Meat', '190,10', '0,31'],
['Italy', 'Meat', '189,32', '0,45'],
['Italy', 'Meat', '188,61', '0,67'],
['Italy', 'Meat', '188,01', '0,72'],
['Italy', 'Meat', '187,36', '0,80'],
]
我有一个代码正在检查以下内容:
index[2]
的my_list
是index[3]
在 my_values == 0,78
index[2]
的my_list
是index[3]
在 my_values == 0,40
index[2]
我n my_list
是index[3]
在 my_values == 0,67
现在我有一个问题,如您所见0,78
,my_values
摩洛哥和西班牙都存在,我只想检查摩洛哥。
这是我的代码:
yet_another_list = [i[2] for i in my_list if i[3] in my_values]
print(yet_another_list)
这是我的输出:
['188,49', '189,01', '187,95', '188,61']
这是我的首选输出:
['188,49', '189,01', '188,61']
正如你可以看到我想要index[1]
的my_values
仅被用于Morocco
和index[2]
对Spain
等..请注意,我officla数据集my_lists
包含了更多的国家...
#添加。我什至尝试了Pandas,但仍收到相同的输出。
df=pd.DataFrame(my_list)
df['Filter']=np.where([i in my_values for i in df[3]],"Yes","")
my_out_list=list(df[2][df['Filter']=='Yes'])
print(my_out_list)
>>
['188,49', '189,01', '187,95', '188,61']
将原始数据结构与迭代器一起使用。
def get_values(my_list_, *my_values_):
''' Finds the desired result using my_list_ and my_values
my_valuesis one or more list
'''
output = []
# Find values for each list in my_values_
for my_values__ in my_values_:
# Create iterators
result = []
my_values_iter = iter(my_values__) # iterator for current list of values
my_list_iter = iter(my_list_) # from beginning of my_list_
v = next(my_values_iter, None)
i = next(my_list_iter, None)
while v and i:
if v == i[3]:
# found match
result.append(i[2])
v = next(my_values_iter, None) # Next value to find in my_values
i = next(my_list_iter, None) # Next value to check in my_list
else:
# try next value from my_list
i = next(my_list_iter, None) # Next value to check in my_list
output.append(result)
if len(output) == 1:
return output[0] # Only single list
else:
return tuple(x for x in output) # Output tuple of lists
用法
# Single list of values
a = get_values(my_list, ['0,78', '0,40', '0,67'])
print(f'a = {a}') # Output: a = ['188,49', '189,01', '188,61']
# Two list of values (can handle an arbitrary number)
a, b = get_values(my_list, ['0,78', '0,40', '0,67'], ['0,78', '0,10', '0,78'])
print(f'a = {a}, b = {b}') # Output: a = ['188,49', '189,01', '188,61'], b = ['188,49', '190,76', '187,95']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句