Python 将字符串排序到字典中,其中初始字符是键,值是以该字符开头的所有行的列表
情况:AHLTA,一种电子病历,将GUI模板导出为文本。我正在构建一个模板编辑器,需要导入文本文件。每行表示一个GUI元素,并以一个数字开头,该数字标识GUI中的父选项卡。行的顺序不重要。我正在使用Python 3 示例(文件): 这似乎是一个恰当的循环,但我最终得到了一个空对:Python 将字符串排序到字典中,其中初始字符是键,值是以该字符开头的所有行的列表,python,list,dictionary,Python,List,Dictionary,情况:AHLTA,一种电子病历,将GUI模板导出为文本。我正在构建一个模板编辑器,需要导入文本文件。每行表示一个GUI元素,并以一个数字开头,该数字标识GUI中的父选项卡。行的顺序不重要。我正在使用Python 3 示例(文件): 这似乎是一个恰当的循环,但我最终得到了一个空对: {3: []} 3: [] 摘要:只有在运行时才知道列表的数量,如何创建列表字典 def main(): # I'm assuming you can get this far... lines =
{3: []}
3: []
摘要:只有在运行时才知道列表的数量,如何创建列表字典
def main():
# I'm assuming you can get this far...
lines = [
'1,some stuff 1',
'2,some stuff 2,more stuff',
'2,some stuff 4,candy,bacon',
'3,some stuff 3,this,is,horrible...'
]
# Something to hold your parsed data
data = {}
# Iterate over each line of your file
for line in lines:
# Split the data apart on comma per your example data
parts = line.split(',')
# denote the key is the first part of the split data
key = parts[0]
if key not in data:
# Since there could be multiple values per key we need to keep a
# list of mapped values
data[key] = []
# put the "other data" into the list
index_of_sep = line.find(',')
data[key].append(line[index_of_sep+1:])
# You probably want to return here. I'm printing so you can see the result
print(data)
if __name__ == '__main__':
main()
结果
C:\Python35\python.exe C:/Users/Frito/GitSource/sandbox/sample.py
{'3': ['some stuff 3,this,is,horrible...'], '1': ['some stuff 1'], '2': ['some stuff 2,more stuff', 'some stuff 4,candy,bacon']}
Process finished with exit code 0
不要写“废话废话”,而是要确保你的问题格式正确,这样我们在阅读时就不会被抓住。你能不能也展示一个输出示例?具体到@cosinepenguine的观点,就是你目前拥有的代码,你得到的成果和你想要的成果对帮助你的社区来说是最有益的:-)为这些废话道歉;浏览器出错,无法预览文本!是否可以删除下一票?这里我有一个字符串形式的键。如果你真的需要它是一个数字类型,这里有很多关于如何做到这一点的答案:-)弗里托,谢谢你。我很惊讶你从早期的发布事故中发现了我想要什么!哈,没问题。很高兴这有帮助!感谢您接受答案:-D
{3: []}
3: []
def main():
# I'm assuming you can get this far...
lines = [
'1,some stuff 1',
'2,some stuff 2,more stuff',
'2,some stuff 4,candy,bacon',
'3,some stuff 3,this,is,horrible...'
]
# Something to hold your parsed data
data = {}
# Iterate over each line of your file
for line in lines:
# Split the data apart on comma per your example data
parts = line.split(',')
# denote the key is the first part of the split data
key = parts[0]
if key not in data:
# Since there could be multiple values per key we need to keep a
# list of mapped values
data[key] = []
# put the "other data" into the list
index_of_sep = line.find(',')
data[key].append(line[index_of_sep+1:])
# You probably want to return here. I'm printing so you can see the result
print(data)
if __name__ == '__main__':
main()
C:\Python35\python.exe C:/Users/Frito/GitSource/sandbox/sample.py
{'3': ['some stuff 3,this,is,horrible...'], '1': ['some stuff 1'], '2': ['some stuff 2,more stuff', 'some stuff 4,candy,bacon']}
Process finished with exit code 0