【问题标题】:match line number of a 1d array with first element of a 2d array for large dataset in Python将一维数组的行号与 Python 中大型数据集的二维数组的第一个元素匹配
【发布时间】:2020-12-16 21:47:32
【问题描述】:

我有两个大列表 - 在这里我将仅展示一个简化示例。

list1我有几句话,

list1 = ['hello','stack','overflow']

list2中,我有list1的单词的行号,以及一个用于标识单词类型的数值。

list2= [['0','10'],['2', '11'],['4', '12']]

我想用list2的行号

list2 = [['0','10'],['2', '11'],['4', '12']] #line numbers here are: 0,2,4

与list1中的对应行,

list1 = ['hello','stack','overflow'] #correspondences found here are: hello (for list2[0]) and overflow (for list2[1])

这样我就可以拥有一个带有单词及其标签的 list3。

list3 = [['hello','10'], ['overflow', '11']]

我找到了一种跨越两个列表的方法,但它非常慢,而且我认为根本没有效率。如何简化此查找过程?

list1 = ['hello','stack','overflow']

list2= [['0','10'],['2', '11'],['4', '12']]


for i in range(0, len(list1)):
    for k in range(0, len(list2)):
        if (str(list2[k][0]) == str(i)):
            print("Found "+str(list1[i]))

找到你好 发现溢出

【问题讨论】:

  • 在您的代码中您似乎使用i 作为索引,因此当您将该索引与list2[k][0] 进行比较时,您实际上在位置2 处溢出,但是类型 11。根据您想要的 list3,我不确定这是您想要的。
  • 为什么输出是['overflow', '12']不应该是['overflow', '11']
  • 修正@DaniMesejo 写错了

标签: python arrays list lookup


【解决方案1】:

IIUC,你可以这样做:

list1 = ['hello', 'stack', 'overflow']
list2 = [['0', '10'], ['2', '11'], ['4', '12']]

# transform the line numbers to ints
line_numbers = [(int(l), e) for l, e in list2]

# filter and compound with other number
res = [[list1[ln], other] for ln, other in line_numbers if ln < len(list1)]

print(res)

输出

[['hello', '10'], ['overflow', '11']]

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多