>>> data= ['hello','world','# ignorethis','xlable: somethingx','ylable: somethingy']
>>> x, y, z = [item.split(':')[-1].strip() for item in data
if not item.startswith('#')][:3]
>>> x
'hello'
>>> y
'world'
>>> z
'somethingx'
说明:
item.startswith('#')过滤以'#'开头的项。如果要检查字符串中任何位置的'#',那么使用if '#' not in item。
item.split(':')在':'处拆分字符串并返回一个列表:
示例:
^{pr2}$
在Python3中,您还可以执行以下操作:
x, y, z, *rest = [item.split(':')[-1].strip() for item in data
if not item.startswith('#')]
使用列表理解:
说明:
item.startswith('#')
过滤以'#'
开头的项。如果要检查字符串中任何位置的'#'
,那么使用if '#' not in item
。item.split(':')
在':'
处拆分字符串并返回一个列表:示例:
^{pr2}$在Python3中,您还可以执行以下操作:
相关问题 更多 >
编程相关推荐