我想从列表中读取
data= ['hello','world','# ignorethis','xlable: somethingx','ylable: somethingy']
我的目标:
- 我想将列表中的这些字符串分配给不同的变量,以便我给出
'hello'tox和'world'toy,类似的东西。 - 忽略带有 的字符串
#。 - 只读取
somethingx变量z而不是'xlable: somethingx'.
使用列表推导:
>>> 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(':')拆分字符串':'并返回一个列表:
例子:
>>> 'xlable: somethingx'.split(':')
['xlable', ' somethingx']
>>> 'hello'.split(':')
['hello']
在 Python3 中,您还可以执行以下操作:
x, y, z, *rest = [item.split(':')[-1].strip() for item in data
if not item.startswith('#')]