Python: 如何从列表的元素中检索一些值?

Python: how to retrieve some values from the elements of a list?

我有一个这样的元素列表:

mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]

如何仅提取事件的 "number" 并生成另一个列表,例如:

extracted_list=['100','17','1000',...]?

为此使用 map 函数:

>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]

你可以使用 'regex' ....

>>> import re
>>> mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
>>> [re.findall('_(\d+)', i)[0] for i in mylist]

['100', '17', '1000']

您可以对 event_ 使用 lstrip,然后对 'of' 使用 split

res = [i.lstrip('event_').split('of')[0] for i in mylist]

print(res)
['100', '17', '1000']

编辑

res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]

print(res)
[100, 17, 1000]

使用列表理解和正则表达式:

import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]
extracted_list = [re.search("\d+", x).group(0) for x in mylist]

我也会用 re

import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
list_id_of = [re.search("event_(\d+)of(\d+)", e).groups() for e in mylist]

[('100', '1000'), ('17', '1000'), ('1000', '1000')]

您可以使用地图:

  events = map(lambda x: x.split('of')[0], mylist)
  map(lambda x: x.split('_')[1], events)

重新使用

import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
pattern = re.compile(r'^event_(\d+).')

mylist = list(map(lambda x : pattern.findall(x)[0] , mylist))
print(mylist)
#['100', '17', '1000']