リストから読みたい
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('#')]