-3

リストから読みたい

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

私の目標:

  1. リスト内のこれらの文字列を別の変数に割り当てたいので、'hello'tox'world'to y、そのようなものを与えます。
  2. で文字列を無視します#
  3. の代わりにsomethingx変数にのみ読み取ります。z'xlable: somethingx'
4

1 に答える 1

4

リスト内包表記の使用:

>>> 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(':')で文字列を分割し':'、リストを返します。

例:

>>> '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('#')]
于 2013-11-07T12:51:07.493 に答える