سؤال

How can I return the trailing set of numbers from a list of strings?

mylist = ['kys_q1a2','kys_q3a20','kys_q2889b244','sonyps3_q92c288888']

expected result:

[2, 20, 244, 288888] 

My failed attempt:

for item in mylist:
    print item[-1]

Context:

Each item in the list represents question name and consist of 2 parts:

  1. question name and number: "kys_q1"
  2. question element name and number: "a2"

I've tried to show the various ways they can be shown.

هل كانت مفيدة؟

المحلول

You can use regex:

>>> import re
>>> r = re.compile(r'\d+$')
>>> [int(m.group()) for m in (r.search(item) for item in mylist) if m]
[2, 20, 244, 288888]

نصائح أخرى

You could use a regex to match the trailing number:

>>> mylist = ['kys_q1a2','kys_q3a20','kys_q2889b244','sonyps3_q92c288888']
>>> [int(re.search(r'\d+$', el).group(0)) for el in mylist]
[2, 20, 244, 288888]
>>> [ int(re.findall('(\d+$)', x)[0]) for x in mylist ]
[2, 20, 244, 288888]
>>>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top