我有這個字串"[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"作為輸入。如何使用遞回或迭代將此字串轉換為串列,但在 Python 中沒有匯入?
這是我嘗試過的。此解決方案僅適用于"[1,[2,3]]"我輸入的字串部分。
預期的輸出是 [1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
def convert(l,out=[],i=0):
while i<len(l)-1:
if l[i] == "]":
return out,i
if l[i] =="[":
out_to_add,index = convert(l[i 1:],[])
out.append(out_to_add)
i =index
elif l[i]!=",":
out.append(l[i])
i =1
print(convert(l)[0][0])
編輯:NB。這是一項任務,不允許匯入
uj5u.com熱心網友回復:
保持嵌套水平
使用ast.literal_eval:
from ast import literal_eval
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
literal_eval(l)
輸出: [1, [2, 3], [4, 5, 6], [7, [8, 90], 10], [11, 120, [13]]]
平單
使用正則運算式,去掉所有括號并拆分:
import re
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
re.sub('[][]', '', l).split(',')
輸出: ['1', '2', '3', '4', '5', '6', '7', '8', '90', '10', '11', '120', '13']
對于整數:
list(map(int, re.sub('[][]', '', l).split(',')))
輸出: [1, 2, 3, 4, 5, 6, 7, 8, 90, 10, 11, 120, 13]
uj5u.com熱心網友回復:
更短的無匯入解決方案:
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
def to_list(d):
while d and (n:=d.pop(0)) != ']':
if n == '[':
yield list(to_list(d))
elif n.isdigit():
yield int(n (x:=lambda :'' if not d[0].isdigit() else d.pop(0) x())())
print(next(to_list(list(l))))
輸出:
[1, [2, 3], [4, 5, 6], [7, [8, 90], 10], [11, 120, [13]]]
uj5u.com熱心網友回復:
以下解決方案可以讓您無需任何匯入即可獲得所需的內容(該解決方案本質上是基于逐個掃描字符,并相應地采取行動):
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
def list_parse(s):
open_lists = []
current_number = ""
for c in s:
if c == "[":
current_list = []
open_lists.append(current_list)
elif c in "0123456789":
current_number = c
continue
elif c == "," or c == "]":
if len(current_number) > 0:
current_list.append(int(current_number))
current_number = ""
if c == "]":
ll = open_lists.pop()
if len(open_lists) == 0:
return ll
else:
current_list = open_lists[-1]
current_list.append(ll)
raise ValueError("Check that the passed list is well formed (are all the parenthesis matched?)")
try:
print(list_parse(l))
except ValueError as e:
print(e)
從我使用格式錯誤的輸入 l(不匹配的括號)運行的少數測驗中 - 應該引發例外。
uj5u.com熱心網友回復:
因為當i超過長度時你沒有回傳任何東西,它不會繼續
嘗試這個
l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
def convert(l,out=[],i=0):
while i<len(l) and l[i] != "]":
if l[i] =="[":
if i<len(l):
out_to_add,index = convert(l[i 1:],[])
out.append(out_to_add)
i =index 2
elif l[i]!=",":
out.append(l[i])
i =1
return out,i
print(convert(l)[0][0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/350401.html
下一篇:傳遞輸入值后不更新屬性
