Python:如果字符串以列表中的字符串开头
我正在读取一个文件,每行都有一个标记,后面是冒号,然后是我想要的信息。示例文件如下所示Python:如果字符串以列表中的字符串开头,python,loops,dictionary,apt,Python,Loops,Dictionary,Apt,我正在读取一个文件,每行都有一个标记,后面是冒号,然后是我想要的信息。示例文件如下所示 Package: com.something.something Section: Utilities Name: Something 等等,(如果你想知道的话,这是一个apt软件包索引) 所以我想循环遍历每一行,看看这一行是否以列表中的一个元素开头。我在想 PkgInfo={} Tags=['Package', 'Section', 'Name'] for line in reader.readlines
Package: com.something.something
Section: Utilities
Name: Something
等等,(如果你想知道的话,这是一个apt软件包索引)所以我想循环遍历每一行,看看这一行是否以列表中的一个元素开头。我在想
PkgInfo={}
Tags=['Package', 'Section', 'Name']
for line in reader.readlines()
if line.startswith(element in Tags):
PkgInfo[element]=line.split(': ')[1]
这段代码不起作用,但希望您理解我的意图。我将如何实现这一点?您需要迭代标记:
PkgInfo={}
Tags=['Package: ', 'Section', 'Name']
for line in reader.readlines():
for tag in Tags:
if line.startswith(tag):
PkgInfo[tag]=line.split(': ')[1]
break
我想试试这样的东西:
PkgInfo={}
#I assume it should be 'Package' not 'Package: '
Tags=['Package', 'Section', 'Name']
for line in reader.readlines()
k, v = line.split(': ')
if k in Tags:
PkgInfo[k] = v
甚至更快更脏的双排:
#I assume it should be 'Package' not 'Package: '
Tags=['Package', 'Section', 'Name']
PkgInfo = dict(line.split(': ') for line in reader.readlines() if line.split(': ')[0] in Tags)
逻辑略有不同的工作解决方案:
PkgInfo={}
Tags=['Package', 'Section', 'Name']
for line in reader.readlines():
entry = line.strip().split(': ', 2)
if len(entry) != 2:
continue
element, value = entry[0], entry[1]
if element in Tags:
PkgInfo[element] = value
print PkgInfo
还要注意的是,元素上的迭代并不是唯一的问题
Tags
中的Package被定义为“Package:”,Tags
在循环中被引用为Tags
,split.line
而不是line.split()
,值不会被剥离。我建议您只需在:
处拆分行,然后测试第一部分是否是您的关键字之一。这可以通过使用set
和中的操作符轻松完成:
tags = set(['Package', 'Section', 'Name'])
pkgInfo = {k: v.strip() for k, v in (line.split(':') for line in reader) if k in tags}
或更长的版本:
tags = set(['Package', 'Section', 'Name'])
pkgInfo = {}
for line in reader:
k, v = line.split(':')
if k in tags:
pkgInfo[k] = v.strip()
但请注意,如果每行中没有一个冒号,则此操作将失败。请尝试以下操作:
PkgInfo = {}
Tags = ['Package', 'Section', 'Name']
for line in reader.readlines():
for element in Tags:
if line.startswith(element):
PkgInfo[element] = line.split(': ')[1]
break
基于split()的所有解决方案的问题是,如果冒号出现多次,它们可能会中断。这不太优雅,但更坚固:
PkgInfo = {}
Tags = ['Package','Section','Name']
splitter = ': '
splitLen = len(splitter)
for line in reader.readlines():
firstColon = line.find(splitter)
if firstColon > 0:
key = line[:firstColon]
if key in Tags:
pkgInfo[key] = line[firstColon + splitLen:]
似乎不是他想要的。请注意,当一个字符串以给定集合中的多个字符串开头时。添加了一个break
。然而,考虑到他的示例代码,这是不可能的。我只是想指出这一点。现在看起来很好Pno不需要道歉,发生在每个人身上!只要纠正它,评论就变得多余了!;-)我觉得这个解决方案特别优雅,可能是因为它最好地集成到了我现有的代码中但是这里还有很多其他的好答案!只是这个对我最合适。:)