【问题标题】:How to compare values in two lists in Python?如何在 Python 中比较两个列表中的值?
【发布时间】:2021-04-10 03:13:06
【问题描述】:

我有 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'],
]

我有一个正在检查以下内容的代码:

  1. 对于摩洛哥,它检查index[2] inmy_listisindex[3]in my_values == 0,78
  2. 对于西班牙,它检查index[2] inmy_list isindex[3]in my_values == 0,40
  3. 对于意大利,它检查index[2] in my_list isindex[3]in my_values == 0,67

现在我有一个问题,您可以看到my_values 中的0,78 存在于摩洛哥和西班牙,我只想让它检查摩洛哥。

这是我的代码:

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']

如您所见,我希望my_values 中的index[1] 仅用于Moroccoindex[2] 用于Spain 等...请注意,在我的官方数据集中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']

【问题讨论】:

  • 您误用了一个值作为不是唯一标识符的唯一标识符。
  • 当有人留下评论而不是答案时,通常意味着他们没有完整的解决方案。不妨查看help center 以更好地了解该网站的运作方式。
  • 切换到 Pandas 但复制相同的错误显然不能解决问题,尽管它可能会很好地扩展。

标签: python list indexing


【解决方案1】:

使用带有迭代器的原始数据结构。

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']

【讨论】:

  • @DarryIG,这看起来不错。不能再短一点吗?不过,我还有另一个补充。如果我有另一个名为 my_values_2 的额外列表,其中也包含 3 个值。我可以复制粘贴代码,但我更喜欢一次性完成...
  • @TanGerCity——意味着你想要来自 my_values_1 和 my_values_2 的结果列表。 my_values_2 是从头开始检查 my_list 还是从 my_values_1 在 my_list 中停止的位置继续?
  • @DarryIG,它又从头开始了。它实际上又是同一件事,只是my_values_2中的值不同
  • @TangerCity--已更新以处理 1 个或多个值列表。
  • @DarryIG 但这意味着我也应该有 2 个输出列表.....
【解决方案2】:

我建议使用字典,然后过滤您的数据集

my_values = {'Morocco': '0,78', 'Spain': '0,40', 'Italy': '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'],
]


print([e[2] for e in filter(lambda x: x[3] == my_values[x[0]], my_list)])

>>> ['188,49', '189,01', '188,61']

附带说明,如果您正在处理更大的数据集,查看 pandas 包可能会有所帮助,这是一个流行的用于数据分析的 Python 库

【讨论】:

  • 我理解你的答案,但它不能解决我更大的数据集。你知道如何用 Pandas 解决这个问题吗?
  • 为什么你认为这不适用于更大的数据集?
  • @tripleee 因为我需要手动修复my_values
  • 这并不是一个糟糕的答案。您当前的数据结构很麻烦,并且可能会引入其他问题。
  • 好的,那么使用 pandas 并不能真正解决这个问题。如果my_list 中的城市顺序与my_values 中值的顺序相匹配,那么您可以通过一些额外的处理来使用它。
【解决方案3】:

如果我正确理解您的要求,您想遍历列表中的国家,同时遍历另一个列表中的索引?

previous = my_list[0][0]
ind = 0
result = []
for item in my_list:
    if item[0] != previous:
        ind += 1
        previous = item[0]
    if item[3] == my_values[ind]:
        result.append(item[2])
print(result)

如果您的国家/地区多于my_values 中的值,这显然会抛出IndexError

也许更好的方法是将my_list 转换为 dict,其中键是国家/地区名称,值是该国家/地区的值。

【讨论】:

  • 您的回答说索引超出范围。我什至尝试过 pandas,但仍然收到相同的输出。
  • 现在试试;我忘了更新previous 变量。
猜你喜欢
  • 2016-04-17
  • 2016-01-04
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多