从字符串python获取一些数据

2024-03-28 17:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根弦,像:

u'c-100001,e-100001,e-100011,e-100009'

我想得到这样的价值

[100001,100011,100009]

我试过:

l = note_to.split('-')
k = length(l)
j=[]
for i in (0,k):
   if k!==0 & k%2!= 0:
      j.append(l[i])

我是说我用了回路。你知道吗


Tags: toinforiflengthnotesplit价值
3条回答

在逗号处拆分字符串并使用列表:

[int(el[2:]) for el in note_to.split(',') if el.startswith('e-')]

我假设您只想得到以e-开头的值;如果您想要不同的东西,您需要澄清您的问题。你知道吗

因为我们已经确定元素以e-开头,所以获取整数值就像跳过前2个字符一样简单。你知道吗

演示:

>>> note_to = u'c-100001,e-100001,e-100011,e-100009'
>>> [int(el[2:]) for el in note_to.split(',') if el.startswith('e-')]
[100001, 100011, 100009]

如果您只想获得唯一的值,并且顺序无关紧要,请使用一个集合,并使用str.rpartition()分割起始字符串(可能超过2个字符,或者总共缺少):

set(int(el.rpartition('-')[-1]) for el in note_to.split(','))

根据你的具体需要,你可以随时把它写回清单。你知道吗

演示:

>>> set(int(el.rpartition('-')[-1]) for el in note_to.split(','))
set([100001, 100011, 100009])
>>> list(set(int(el.rpartition('-')[-1]) for el in note_to.split(',')))
[100001, 100011, 100009]

将列表理解与str.startswithstr.split一起使用:

>>> s = u'c-100001,e-100001,e-100011,e-100009'
>>> [int(x.split('-')[1]) for x in s.split(',') if x.startswith('e-')]
[100001, 100011, 100009]

如果您希望所有的项目不只是以e-开头,那么删除if x.startswith('e-')部分。你知道吗

>>> [int(x.split('-')[1]) for x in s.split(',')]
[100001, 100001, 100011, 100009]

在中,您只需要唯一的项,然后将列表传递给set()或将set与生成器表达式一起使用。你知道吗

您可以按以下步骤进行:

string = 'c-100001,e-100001,e-100011,e-100009'
your_list = string.split(',e-')[1:]

>>> your_list
[100001,100011,100009]

相关问题 更多 >