有沒有比.txt文件更簡單的方法在Python上從.txt文件創(chuàng)建字典:for y in open('bones.txt'): bones={','.join(y:'0')}其中bones.txt包含:AnkylosaurusPachycephalosaurusAnkylosaurusTyrannosaurus RexAnkylosaurusStruthiomimusStruthiomimus
3 回答

青春有我
TA貢獻1784條經(jīng)驗 獲得超8個贊
with open("bones.txt") as f:
my_dict = dict.fromkeys(f, '0')
感謝您的建議,我在上面得到了這個答案。
使用dict代替{}
不要使用readlines。該file iterator作品
清理換行符,也許我們可以使用os.linesep
import os
with open("bones.txt") as f:
my_dict = dict.fromkeys(map(lambda x: x.replace(os.linesep, ""), f), '0')

慕虎7371278
TA貢獻1802條經(jīng)驗 獲得超4個贊
也可以修改此方法以包含鍵的值,而不會使其太復雜:
bones = {}
for y in open('bones.txt'):
bones[y.strip('\n')] = '0'
添加回答
舉報
0/150
提交
取消