将Y列表中的项目附加到X列表Python中的一个特定列表中

时间:2016-04-09 00:53:47

标签: python list python-2.7 append list-comprehension

我有两个列表xy

x列表里面有几个列表。例如:

x = [['1', 'hello', 'a'], ['3', 'hello', 'b'], ['11', 'hello', 'c'], ['2', 'hello', 'd'], ['4', 'hello', 'e'], ['22', 'hello', 'f']]

y列表是一个列表。里面的项目是网址,其中包含 x 列表中每个列表的信息。

y = ['odd1', 'even2', 'odd3', 'even4', 'odd11', 'even22']

我从网络抓取中获取了信息。所以我试图将y列表中的单个项目附加到x列表中的单个列表中。例如,y[0]项应附加到x[0]列表,但y[1]项应附加到x[3]

这是我正在寻找的输出:

output = [['1', 'hello', 'a', 'odd1'], ['3', 'hello', 'b', 'odd3'], ['11', 'hello', 'c', 'odd11'], ['2', 'hello', 'd', 'even2'], ['4', 'hello', 'e', 'even4'], ['22', 'hello', 'f', 'even22']]

我不知道如何编码这些信息。首先,对y列表中的项目进行排序,但x列表中的列表不是。但是,他们有一个模仿者。它们从我抓取的奇数行的信息开始,然后是来自偶数行的信息。

我尝试过这些,以便首先对x列表进行排序:

1. x.sort(key=int)
2. sorted(x) | Result [['1...'], ['11...], ['2...'], ['22...'], ['3...]...]
3. x = [int(x) for x in x]

我怎么都没有好结果。

另一方面,我尝试以这种简单的方式将y列表中的项目附加到x列表:

for i in x:
    i.append(y[:])

很明显,y列表中的所有项目都附加在x

的每个列表中

如何解决此代码。谢谢!

3 个答案:

答案 0 :(得分:1)

x = [['1', 'hello', 'a'],
     ['3', 'hello', 'b'],
     ['11', 'hello', 'c'],
     ['2', 'hello', 'd'],
     ['4', 'hello', 'e'],
     ['22', 'hello', 'f']]

y = ['odd1', 'even2', 'odd3', 'even4', 'odd11', 'even22']

x = sorted(x, key=lambda i: int(i[0]))
y = sorted(y, key=lambda i: int(i.replace('even', '').replace('odd', '')))

print y

result = [a + [b] for a, b in zip(x, y)]
print result #prints out [['1', 'hello', 'a', 'odd1'], ['3', 'hello', 'b', 'odd3'], ...]

答案 1 :(得分:1)

试试这个

x = [['1', 'hello', 'a'], ['3', 'hello', 'b'], ['11', 'hello', 'c'], ['2', 'hello', 'd'], ['4', 'hello', 'e'], ['22', 'hello', 'f']]
y = ['odd1', 'even2', 'odd3', 'even4', 'odd11', 'even22']
x.sort(key=lambda z: int(z[0]))
for i in range(0, len(x)):
    x[i].append(y[i])
print(x)

输出:

[['1', 'hello', 'a', 'odd1'], ['2', 'hello', 'd', 'even2'], ['3', 'hello', 'b', 'odd3'], ['4', 'hello', 'e', 'even4'], ['11', 'hello', 'c', 'odd11'], ['22', 'hello', 'f', 'even22']]

答案 2 :(得分:1)

使用

重新排序y
In [6]: y[::2]+y[1::2]
Out[6]: ['odd1', 'odd3', 'odd11', 'even2', 'even4', 'even22']

然后,您可以使用y将重新排序的xzip配对:

x = [['1', 'hello', 'a'], ['3', 'hello', 'b'], ['11', 'hello', 'c'], 
     ['2', 'hello', 'd'], ['4', 'hello', 'e'], ['22', 'hello', 'f']]
y = ['odd1', 'even2', 'odd3', 'even4', 'odd11', 'even22']
print([xi+[yi] for xi, yi in zip(x, y[::2]+y[1::2])])

产量

[['1', 'hello', 'a', 'odd1'],
 ['3', 'hello', 'b', 'odd3'],
 ['11', 'hello', 'c', 'odd11'],
 ['2', 'hello', 'd', 'even2'],
 ['4', 'hello', 'e', 'even4'],
 ['22', 'hello', 'f', 'even22']]
相关问题