簡體   English   中英

Python - 創建包含多個子列表的列表

[英]Python - Create list with multiple sub-lists

我需要做的很簡單,但我無法弄清楚如何。

我在列表中組織了很多字符串:

list = ['my name is Marco and i'm 24 years old', 'my name is Jhon and i'm 30 years old']

我使用正則表達式從列表的每個元素中提取信息:

for element in list:
  name = re.findall('my name is (.*?) and i\'m', element, re.DOTALL)[0]
  age = re.findall('and i\'m (.*?) years old', element, re.DOTALL)[0]

現在我想要做的是重新編譯一個新的列表,該列表包含按名稱和年齡組成的元素子列表。

例:

for element in newlist:
  name = element[0]
  age = element[1]

可以這樣做嗎?

以下是完全按照您的意願執行的解決方案。 這將創建一個新列表,其中包含具有名稱和年齡的子列表。

new_list = []
for element in list:
   name = re.findall('my name is (.*?) and i\'m', element, re.DOTALL)[0]
   age = re.findall('and i\'m (.*?) years old', element, re.DOTALL)[0]
   new_list.append([name, age])

您可以使用簡單的列表理解來執行您想要的操作:

name_pat = re.compile('my name is (.*?) and i\'m', re.DOTALL)
age_pat = re.compile('and i\'m (.*?) years old', re.DOTALL)

new_list = [[name_pat.findall(elem)[0], age_pat.findall(elem)[0]] for elem in your_list]

首先,您不需要兩個正則表達式來為名稱和年齡選擇兩個值。

>>> s = "my name is Marco and i'm 24 years old"
>>> pattern = r"my name is\s+(.+)\s+and i'm\s+(\d+)\s+years old"
>>> m = re.match(pattern, s)
>>> print(m.groups())
('Marco', '24')

您可以使用列表推導來構建新列表:

>>> data = ["my name is Marco and i'm 24 years old", "my name is Jhon and i'm 30 years old"]
>>> new_list = [re.match(pattern, s).groups() for s in data]
>>> print(new_list)
[('Marco', '24'), ('Jhon', '30')]

結果是一個元組列表。 如果您確實需要列表列表,可以執行以下操作:

new_list = [list(re.match(pattern, s).groups()) for s in data]

列表理解是這個循環的簡寫:

new_list = []
for s in data:
    m = re.match(pattern, s)
    if m:
        new_list.append(m.groups())

這個循環和列表理解之間的主要區別在於前者可以處理與模式不匹配的字符串,而列表理解假定模式將始終匹配(如果不匹配則會產生異常)。 你可以在列表理解中處理這個問題,然而,它開始變得丑陋,因為你需要執行兩次正則表達式匹配:一次檢查模式是否匹配,然后再次提取實際值。 在這種情況下,我認為顯式for循環更清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM