-4

我有如下代码:

a = [[0, 'CN1101'], [1, 'CN1602'], [2, 'CN1601']]   
b = [[0, 'CN1601'], [1, 'CN1101'], [2, 'CN1101'], [3, 'CN1602']]   
c = []   
d = []  

for i in range(len(a)):
    for j in range(len(b)):
        if a[i][1] == b[j][1]:
            c.append(b[j][0])
    d.append(c)

结果是d = [[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 3, 0]]
我想要结果d = [[1,2],[3],[0]]。你将如何编码?

4

3 回答 3

0

我会这样做:

a = ['CN1101', 'CN1602', 'CN1601']   
b = ['CN1601', 'CN1101', 'CN1101', 'CN1602']   
d = {}

for i in range (0, len(a)):
    d[i] = [j for j in range(0, len(b)) if b[j] == a[i]]
print d

您想将第二个列表中的索引链接到第一个列表中的定义,我认为使用字典更适合您的情况。请注意,该程序仍将在O(N^2). 在这种情况下,输出将是:

{0: [1, 2], 1: [3], 2: [0]}

请注意,将迭代的行更改为:

d[a[i]] = [j for j in range(0, len(b)) if b[j] == a[i]]

将产生:

{'CN1101': [1, 2], 'CN1601': [0], 'CN1602': [3]}

如果列表是您想要的而不是字典,那么这将是您的解决方案:

a = ['CN1101', 'CN1602', 'CN1601']   
b = ['CN1601', 'CN1101', 'CN1101', 'CN1602']   
d = []

for i in range (0, len(a)):
    d.append([j for j in range(0, len(b)) if b[j] == a[i]])
print d

输出是:

[[1, 2], [3], [0]]

请在此处阅读更多内容:

https://docs.python.org/2/tutorial/datastructures.html#dictionaries

于 2019-03-21T09:19:58.060 回答
0

我很感激你的回答。我有其他代码供您参考。

a = [[0, 'CN1101'], [1, 'CN1602'], [2, 'CN1601']]
b = [[0, 'CN1601'], [1, 'CN1101'], [2, 'CN1101'], [3, 'CN1602']]
d = []
    for i in range(0,len(a),1):
        locals()['rowy%s' %i] = []
        for j in range(0,len(b),1):
            if a[i][1] == b[j][1]:
                locals()['rowx%s' %j] = b[j][0]
            elif a[i][1] != b[j][1]:
                continue
            locals()['rowy%s' %i].append(locals()['rowx%s' %j])
        d.append(locals()['rowy%s' %i])`
于 2019-04-03T05:33:14.107 回答
0

我们首先构建一个包含 的数据的 dict b,以 refs 作为键。然后我们可以构建您的输出。

通过这样做,我们只在每个列表上迭代一次。

from collections import defaultdict

a = [[0, 'CN1101'], [1, 'CN1602'], [2, 'CN1601']]   
b = [[0, 'CN1601'], [1, 'CN1101'], [2, 'CN1101'], [3, 'CN1602']]  

bd = defaultdict(list)
for num, ref in b:
    bd[ref].append(num)

# bd will now be  {'CN1601': [0], 'CN1101': [1, 2], 'CN1602': [3]}

out = [bd[ref] for num, ref in a]
print(out)
# [[1, 2], [3], [0]]
于 2019-03-28T12:25:43.397 回答