在列表中搜索字符串python中的值

时间:2013-06-05 08:47:55

标签: python list search

尝试搜索此列表

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,则获取字符串输出

6 个答案:

答案 0 :(得分:3)

for i in a:
    if "1" in i:
        print(i)

答案 1 :(得分: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

答案 2 :(得分:0)

def f(x):
    for i in a:
        if i.strip().startswith(str(x)):
            print i
        else:
            print '%s isnt the population' % (x)

f(1) # or f("1")

这比进行"1" in x样式检查更准确/更具限制,尤其是如果你的句子在字符串中的其他地方有一个非语义'1'字符。例如,如果您有字符串"2 is the 1st in the population"

,该怎么办?

输入数组中有两个语义矛盾的值:

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

这是故意的吗?

答案 3 :(得分:0)

使用list comprehensionin检查string contains是否为“1”字符,例如:

print [i for i in a if "1" in i]

如果你不喜欢Python打印列表的方式,并且你喜欢单独一行的每个匹配,你可以像"\n".join(list)那样包装它:

print "\n".join([i for i in a if "1" in i])

答案 4 :(得分:0)

Python有一个非常方便的find方法。如果未找到则输出-1或具有第一个并发的位置的int。这样您就可以搜索超过1个字符的字符串。

print [i for i in a if i.find("1") != -1]

答案 5 :(得分:0)

如果我理解得很清楚,您希望看到所有条目都以给定数字开头......但重新编号

# The original list
>>> a = ['1 is the population', '1 isnt the population', '2 is the population']

# split each string at the first space in anew list
>>> s = [s.split(' ',1) for s in a]
>>> s
[['1', 'is the population'], ['1', 'isnt the population'], ['2', 'is the population']]

# keep only whose num items == '1'
>>> r = [tail for num, tail in s if num == '1']
>>> r
['is the population', 'isnt the population']

# display with renumbering starting at 1
>>> for n,s in enumerate(r,1):
...   print(n,s)
... 
1 is the population
2 isnt the population

如果你(或你的老师?)喜欢一个衬里,这里有一个捷径:

>>> lst = enumerate((tail for num, tail in (s.split(' ',1) for s in a) if num == '1'),1)
>>> for n,s in lst:
...   print(n,s)
... 
1 is the population
2 isnt the population