的文本以下列方式格式化:提取從文本變量,具有完全不同的格式,使用Python
0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1
在左邊總是有一個號碼,右邊可以有多個。
這就是我試圖產生的,與這種格式的列表。
lst = ['01', '32', '26', '25', '87', '59', '54', '51']
請不要問我到目前爲止所嘗試的是什麼,因爲任何嘗試,使用strip和split,都會導致與我想要看到的內容相距甚遠。
的文本以下列方式格式化:提取從文本變量,具有完全不同的格式,使用Python
0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1
在左邊總是有一個號碼,右邊可以有多個。
這就是我試圖產生的,與這種格式的列表。
lst = ['01', '32', '26', '25', '87', '59', '54', '51']
請不要問我到目前爲止所嘗試的是什麼,因爲任何嘗試,使用strip和split,都會導致與我想要看到的內容相距甚遠。
無論如何都要使用循環。這裏是一個發電機產生的輸出:
def genoutput(iterable):
for line in iterable:
first, second = (l.strip() for l in line.split('->'))
for value in second.split(','):
yield first + value.strip()
現在,您可以遍歷發電機,或輸出轉換到一個列表:
with open('inputfilename') as infh:
lst = list(genoutput(infh))
演示:
>>> example = '''\
... 0 -> 1
... 3 -> 2
... 2 -> 6,5
... 8 -> 7
... 5 -> 9,4,1
... '''.splitlines()
>>> def genoutput(iterable):
... for line in iterable:
... first, second = (l.strip() for l in line.split('->'))
... for value in second.split(','):
... yield first + value.strip()
...
>>> list(genoutput(example))
['01', '32', '26', '25', '87', '59', '54', '51']
該作品:
txt='''\
0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1'''
output=[]
for line in txt.splitlines():
lh, rh=map(str.strip, line.split('->'))
for e in map(str.strip, rh.split(',')):
output.append(lh+e)
print output
# ['01', '32', '26', '25', '87', '59', '54', '51']
理解方法d;
print [i for i in [[x.split(' -> ')[0] + y for y in x.split(' -> ')[1].split(',')]
for x in '''0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1'''.split('\n')] for i in i]
編輯:簡化if語句
遞歸方法;
def paraToListRecur(para):
if para != []:
first = para[0].split(' -> ')
return [first[0]+x for x in first[1].split(',')] + paraToListRecur(para[1:])
return para
data = '''0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1'''.split('\n')
print paraToListRecur(data)
爲什麼沒有循環? – dawg
爲什麼需要不使用循環?你在這裏製作字符串,還是整數? –
@MartijnPieters馬丁我編輯了這個問題。我需要他們是不是整數的字符串。 – Karapapas