简体   繁体   English

如何从包含字符串和整数的列表中提取 integer 个数字的列表?

[英]How to extract a list of integer numbers from a list with strings and integers?

I do have a list which looks like:我确实有一个看起来像这样的列表:

a = ['11, 12, 9, 10, 17, 18, 19, \n', '20, 2, 6, 4, 1, 13, 14, 15, \n', '16, 3, 5, 7, 8, 21, 22, 23, \n', '24, 25, 26, 27, 28, 29, 30, 31, \n', '32, 33, 34, 35, 36, 37, 38, 39, \n', '40, 41, 42, 43, 44, 45, 46, 47, \n', '48, 49, 50, 51, 52, 53, 54, 55, \n', '56, \n']

I want to create a list with each integer in it separately with:我想创建一个列表,其中每个 integer 分别包含:

a = [int(x) for s in a for x in s.split(',')]

I can see the error because of \n and ' but cant find a solution, which should be looking like:我可以看到错误,因为 \n 和 ' 但找不到解决方案,它应该看起来像:

a = [11, 12, 9, 10, 17, 18, 19, 20, 2, 6, 4, 1, 13, 14, 15, 16, 3, 5, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]

Can someone give some solution in this regard?有人可以在这方面提供一些解决方案吗?

you could just add if x != ' \n' to your list-comprehension:您可以将if x != ' \n'添加到您的列表理解中:

a = [int(x) for s in a for x in s.split(',') if x != ' \n']

a more general approach would be this:更一般的方法是这样的:

b = []
for s in a:
    for x in s.split(','):
        try:
            n = int(x)
        except ValueError:
            continue
        b.append(n)

One liner and generic solution for python3: python3 的一种线性和通用解决方案:

a = [...]
res = [int(x.strip()) for s in a for x in s.split(',') if x.strip().isnumeric()]

So to me it looks like you have a list of lines.所以对我来说,您似乎有一个行列表。 You could just do:你可以这样做:

a = [] # line list
ints = [int(i.strip()) for i in ''.join(list).split(',')]

Or you tell us how you got the line list或者你告诉我们你是如何得到行列表的

Juststrip the unwanted characters:只需strip不需要的字符:

a = [int(x) for s in a for x in s.strip(', \n').split(',')]

You could use String.replace() the remove the \n s.您可以使用 String.replace() 删除 \n s。

a = [int(x) for s in a for x in (s.replace(‘, \n’, ‘’)).split(',')]

using regex使用正则表达式

import re
a = ['11, 12, 9, 10, 17, 18, 19, \n', '20, 2, 6, 4, 1, 13, 14, 15, \n', '16, 3, 5, 7, 8, 21, 22, 23, \n', '24, 25, 26, 27, 28, 29, 30, 31, \n', '32, 33, 34, 35, 36, 37, 38, 39, \n', '40, 41, 42, 43, 44, 45, 46, 47, \n', '48, 49, 50, 51, 52, 53, 54, 55, \n', '56, \n']

a = ','.join(a)
res = [int(i) for i in re.findall(r'[0-9]+', a)]
print(res)
# [11, 12, 9, 10, 17, 18, 19, 20, 2, 6, 4, 1, 13, 14, 15, 16, 3, 5, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM