2012-09-23 65 views
1

如果我有一個列表的字符串:追加兩個整數列出「..」的Python

first = [] 
last = [] 

my_list = [' abc 1..23',' bcd 34..405','cda  407..4032'] 

我怎麼會追加側翼..到其對應的列表中的號碼?得到:

first = [1,34,407] 
last = [23,405,4032] 

我不會介意的字符串或者是因爲我可以轉換成int後

first = ['1','34','407'] 
last = ['23','405','4032'] 

回答

3

使用re.search..之間匹配的號碼,並將其存儲在兩個不同的組:

import re 

first = [] 
last = [] 

for s in my_list: 
    match = re.search(r'(\d+)\.\.(\d+)', s) 
    first.append(match.group(1)) 
    last.append(match.group(2)) 

DEMO

+0

什麼是r'期間。 ? 也\ d +做什麼? –

+0

@ draconisthe0ry:'\ d'匹配一個數字,'\ d +'匹配*一個或多個*數字。 'r'是Python的原始字符串符號(http://en.wikipedia.org/wiki/String_literal#Raw_strings)。看看這個其他問題的例子,當不使用'r''會影響你的匹配:http://stackoverflow.com/questions/2241600/python-regex-r-prefix。 –

3

我會使用一個正則表達式:

import re 
num_range = re.compile(r'(\d+)\.\.(\d+)') 

first = [] 
last = [] 

my_list = [' abc 1..23',' bcd 34..405','cda  407..4032'] 

for entry in my_list: 
    match = num_range.search(entry) 
    if match is not None: 
     f, l = match.groups() 
     first.append(int(f)) 
     last.append(int(l)) 

此輸出的整數:

>>> first 
[1, 34, 407] 
>>> last 
[23, 405, 4032] 
2

還有一個解決方案。

for string in my_list: 
    numbers = string.split(" ")[-1] 
    first_num, last_num = numbers.split("..") 
    first.append(first_num) 
    last.append(last_num) 

它會拋出一個ValueError如果在my_list沒有空格的字符串或沒有「」在某些字符串(或最後一個空格後有不止一個「」在字符串的最後一個空格之後)。

事實上,如果您想要確定值是從所有字符串中真正獲得的,並且所有字符串都放在最後一個空格之後,這是件好事。你甚至可以添加一個try ... catch塊來做一些事情,以防它嘗試處理的字符串處於意想不到的格式。

+1

第2行和第3行可以合併爲'first_num,last_num = string.split()[ - 1] .split('..')'。 –

+1

最好的解決方案,在這種情況下,不需要正則表達式。 – jamylak

0
first=[(i.split()[1]).split("..")[0] for i in my_list] 
second=[(i.split()[1]).split("..")[1] for i in my_list]