[英]Using Python's exec() function with formatted string?
我有一個包含學校日程安排的文件,我想從文件的每一行創建一個列表。 該文件看起來像這樣:
first:second:third:fourth:fifth
first:second:third:fourth:fifth
代碼是這樣的:
schedule_file = "school-schedule.txt"
with open(schedule_file) as schedule:
for c, line in enumerate(schedule):
exec("ln%s = schedule.read().split(':')" % str(c+1))
print(ln1)
print(ln2)
print(ln3)
print(ln4)
print(ln5)
print(ln6)
print(ln7)
print(ln8)
print(ln9)
print(ln10)
我知道該文件有十行,這就是為什么,為了測試目的,我希望它打印這十個列表。 不幸的是,似乎將第一行放入名為ln1
的列表中,並為所有其他列表引發了一個NameError異常,從ln2
開始:
['first', 'second', 'third', 'fourth', 'fifth']
Traceback (most recent call last):
File "D:\schedule.py", line 10, in <module>
print(ln2)
NameError: name 'ln2' is not defined
是不是可以在exec()
函數中使用格式化的字符串,還是我犯了一些其他愚蠢的錯誤?
for c, line in enumerate(schedule):
exec("ln%s = schedule.read().split(':')" % str(c+1))
文件中的line
變量line
,但您寫道:
exec("ln%s = schedule.read().split(':')....
代替:
exec("ln%s = line.split(':')...
無論如何,每當你發現自己編寫帶有這樣名字的變量時:
print(ln1)
print(ln2)
print(ln3)
print(ln4)
如果變量名只有一個數字,那么你需要停止你正在做的事情,而是使用一個列表。 如果你有一個名為ln
的列表,那么列表中的項目已經有了名稱ln[0], ln[1]
等。所以,你可以這樣做:
with open('data.txt') as f:
ln = [line.rstrip().split(':') for line in f]
print(ln)
print(ln[0])
print(ln[1])
--output:--
$ cat data.txt
a:b:c:d
e:f:g:h
$ python prog.py
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]
['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']
你已經在第一次迭代后讀取了整個文件,所以你永遠不會超過第一個exec("ln%s = .....
:
exec("ln%s = schedule.read().split(':')" % str(c+1))
^^^
.read() # reads whole/rest of file
只需使用readlines並按索引訪問:
with open(schedule_file) as schedule:
data = schedule.readlines()
ln1 = data[0].split(":")
.....
或者結合地圖分割:
data = list(map(lambda x: x.split(":"),schedule))
你也可以使用一個字典,但它不僅僅是簡單地使用列表和按索引訪問的好處。
如果你真的想要十個變量然后解壓縮:
with open(schedule_file) as schedule:
ln1,ln2 ....ln10 = map(lambda x: x.split(":"),schedule
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.