如何从列表中删除项并使项加入

dtcbnfnu  于 2021-08-25  发布在  Java
关注(0)|答案(3)|浏览(284)

我有一个有数字的列表,但因为它附加到使用for循环的列表中,所以它有'\n',我不知道如何删除它。
列表如下所示

['3', '7', '4', '5', '5', '9', '2', '2', '7', '\n', '4', '3', '7', '1', '5', '9', '4', '3', '0', '\n', '3', '7', '2', '4', '1', '0', '2', '7', '5', '\n', '7', '8', '4', '5', '1', '6', '2', '5', '7', '\n', '2', '8', '0', '6', '6', '1', '1', '2', '3', '\n', '9', '3', '5', '6', '8', '3', '8', '7', '1', '\n', '6', '7', '5', '5', '4', '7', '4', '8', '6']

我要删除“”和'\n',使其看起来像这样

[374559227,437159430,372410275,784516257,280661123,935683871,675547486]
vmpqdwk3

vmpqdwk31#

连接到字符串并拆分换行符:

l = [
    '3', '7', '4', '5', '5', '9', '2', '2', '7', '\n', '4', '3', '7', '1', '5',
    '9', '4', '3', '0', '\n', '3', '7', '2', '4', '1', '0', '2', '7', '5', '\n',
    '7', '8', '4', '5', '1', '6', '2', '5', '7', '\n', '2', '8', '0', '6', '6',
    '1', '1', '2', '3', '\n', '9', '3', '5', '6', '8', '3', '8', '7', '1', '\n',
    '6', '7', '5', '5', '4', '7', '4', '8', '6'
]
print([int(x) for x in ''.join(l).split('\n')])
>>> [374559227, 437159430, 372410275, 784516257, 280661123, 935683871, 675547486]
66bbxpm5

66bbxpm52#

你可以用 itertools.groupby :

>>> from itertools import groupby
>>> lst = ['3', '7', '4', '5', '5', '9', '2', '2', '7', '\n', '4', '3', '7', '1', '5', '9', '4', '3', '0', '\n', '3', '7', '2', '4', '1', '0', '2', '7', '5', '\n', '7', '8', '4', '5', '1', '6', '2', '5', '7', '\n', '2', '8', '0', '6', '6', '1', '1', '2', '3', '\n', '9', '3', '5', '6', '8', '3', '8', '7', '1', '\n', '6', '7', '5', '5', '4', '7', '4', '8', '6']    
>>> [int(''.join(digits)) for is_number, digits in groupby(lst, lambda x: x != '\n') if is_number]
[374559227, 437159430, 372410275, 784516257, 280661123, 935683871, 675547486]
gmxoilav

gmxoilav3#

您可以使用reduce函数

from functools import reduce
lst = ['3', '7', '4', '5', '5', '9', '2', '2', '7', '\n', '4', '3', '7', '1', '5', '9', '4', '3', '0', '\n', '3', '7', '2', '4', '1', '0', '2', '7', '5', '\n', '7', '8', '4', '5', '1', '6', '2', '5', '7', '\n', '2', '8', '0', '6', '6', '1', '1', '2', '3', '\n', '9', '3', '5', '6', '8', '3', '8', '7', '1', '\n', '6', '7', '5', '5', '4', '7', '4', '8', '6']
lst_result = [int(n) for n in reduce(lambda x, y: f"{x}{y}", lst).split('\n')]

输出:

[374559227, 437159430, 372410275, 784516257, 280661123, 935683871, 675547486]

相关问题