0

このリストを検索しようとしています

a = ['1 is the population', '1 isnt the population', '2 is the population']

これが達成可能であれば、値1のリストを検索し、値が存在する場合は文字列を出力します。

出力のために取得したいのは、数値が存在する場合は文字列全体です。値 1 が存在する場合に取得したい出力は、文字列を出力します。いえ

1 is the population 
2 isnt the population 

上記は出力から欲しいものですが、それを取得する方法がわかりません。リストとその文字列で値 1 を検索し、値 1 が表示された場合は文字列出力を取得することは可能ですか?

4

6 に答える 6

3
for i in a:
    if "1" in i:
        print(i)
于 2013-06-05T08:50:21.257 に答える
1

ここで使用する必要がregexあります:

inそのような文字列に対しても True を返します。

>>> '1' in '21 is the population'
True

コード:

>>> a = ['1 is the population', '1 isnt the population', '2 is the population']
>>> import re
>>> for item in a:
...     if re.search(r'\b1\b',item):
...         print item
...         
1 is the population
1 isnt the population
于 2013-06-05T08:55:10.483 に答える
0

Python には非常に便利な find メソッドがあります。見つからない場合は -1 を出力するか、最初に出現した位置の int を出力します。これにより、1 文字を超える文字列を検索できます。

print [i for i in a if i.find("1") != -1]
于 2013-06-05T09:03:57.367 に答える