簡體   English   中英

如何將字符串轉換為列表?

[英]How to convert string to list?

我有一個清單:

sample = ["['P001']"]

如何將其轉換為:

sample = [["P001" ]]

我試過[[x] for x in sample]但 output 是[["[P001]"]]

編輯:對於給您帶來的不便,我深表歉意,因為我在我提出的問題中犯了錯誤。 其實就是"P001"一個字符串。 再次抱歉。

如果你想要 output 作為這個[['P001']] ,你可以這樣做:

>>> sample = ["[P001]"]
>>> [[sample[0].strip('[\]')]]
[['P001']]

但是如果你想要 output 作為[[P001]]我不知道這是否可能。 P001不是 python 類型,如果P001是之前定義的變量,則修改后的列表將保存P001的值而不是名稱本身。 例如:

>>> P001 = 'something'
>>> sample = ["[P001]"]
>>> [eval(sample[0])]
[['something']]

這是一個字符串數組,每個字符串由“[P001]”之類的模式組成。 您需要遍歷外部數組並與每個元素運行匹配以獲取內部值,在本例中為“P001”。 然后你可以 append 你喜歡的值。

s = ["[P001]", "[S002]"]
result = []
import re
for i in s:
    r = re.match(r"\[(.*?)\]", i)
    if r:
        result.append([r.group(1)])

print(result)
[['P001'], ['S002']]

只需對字母數字字符使用正則表達式即可:

sample = ["[P001,P002]","[P003,P004]"]

import re
sample = [re.findall("\w+", sublist) for sublist in sample]

嘗試使用:

print([[i[1:-1] for i in sample]])

暫無
暫無

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

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