在python中如何从列表中分配字符串

2024-05-19 10:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想看一张单子

data= ['hello','world','# ignorethis','xlable: somethingx','ylable: somethingy']

我的目标:

  1. 我想把列表中的这些字符串赋给不同的变量,这样我就把'hello'赋给x,把{}赋给{},类似这样。在
  2. 忽略带有#的字符串。在
  3. 只读取somethingx到变量z,而不是'xlable: somethingx'。在

Tags: 字符串hello目标列表worlddata单子ignorethis
1条回答
网友
1楼 · 发布于 2024-05-19 10:22:21

使用列表理解:

>>> 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'

说明:

  1. item.startswith('#')过滤以'#'开头的项。如果要检查字符串中任何位置的'#',那么使用if '#' not in item

  2. item.split(':')':'处拆分字符串并返回一个列表:

示例:

^{pr2}$

在Python3中,您还可以执行以下操作:

x, y, z, *rest = [item.split(':')[-1].strip() for item in data 
                                                 if not item.startswith('#')]

相关问题 更多 >

    热门问题