0

trying to search this list

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

what i want to do if this is achievable is search the list for the value 1. and if the value exists print the string.

What i want to get for the output is the whole string if the number exists. The output i want to get if the value 1 exists print the string. I.e

1 is the population 
2 isnt the population 

The above is what i want from the output but I dont know how to get it. Is it possible to search the list and its string for the value 1 and if the value of 1 appears get the string output

user2423678
  • 43
  • 1
  • 8
  • 1
    You seem to be describing and showing different things. Did you mean to output one string for each number? – Yann Vernier Jun 05 '13 at 08:53
  • what if `a` contains : `'21 is the population'`? – Ashwini Chaudhary Jun 05 '13 at 08:58
  • 1
    You could have lot less trouble by using the right data structure instead of doing _clever_ parsing. Here a dictionary could have been a better bet. Assuming the double appearance of the '1' **is not** an error, something like that: `a = { 1: ('is the population', 'isnt the population'), 2: ('is the population'), }` – Sylvain Leroux Jun 05 '13 at 12:44

6 Answers6

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

You should use regex here:

in will return True for such strings as well.

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

Code:

>>> 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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
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")

This is more accurate/restrictive than doing a "1" in x style check, esp if your sentence has a non-semantic '1' char anywhere else in the string. For example, what if you have a string "2 is the 1st in the population"

You have two semantically contradictory values in the input array:

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

is this intentional?

Preet Kukreti
  • 8,417
  • 28
  • 36
  • `startswith` seems a little bit to restriced for how the question is worded. –  Jun 05 '13 at 08:51
  • 1
    @Tichodroma I shaped my response based on the example data. However, you are correct if the instructions are accurate. Ill update my response. – Preet Kukreti Jun 05 '13 at 08:57
  • Also note that `startswith` is a lot slower than `a[0]` – michaelmeyer Jun 05 '13 at 08:58
  • 1
    @doukremt unless its an empty string. In which case `a[0]` throws an exception. Which is **much** slower. Not sure about the emphasis on performance; if you are choosing to write code in Python, you are already accepting that it is not a performance oriented solution. If you are serious about performance, and that is a primary concern, you should not be writing this in python in the first place. – Preet Kukreti Jun 05 '13 at 09:03
  • @PreetKukreti: so `a and a[0]`. Also, Python being slow doesn't mean you have to write slow code. When there are alternatives, some may be preferred over other. – michaelmeyer Jun 05 '13 at 09:48
0

Use list comprehension and in to check if the string contains the "1" character, e.g.:

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

In case you don't like the way Python prints lists and you like each match on a separate line, you can wrap it like "\n".join(list):

print "\n".join([i for i in a if "1" in i])
Community
  • 1
  • 1
gertvdijk
  • 24,056
  • 6
  • 41
  • 67
0

Python has a find method which is really handy. Outputs -1 if not found or an int with the position of the first occurrency. This way you can search for strings longer than 1 char.

print [i for i in a if i.find("1") != -1]
luke14free
  • 2,529
  • 1
  • 17
  • 25
  • What is the advantage of [`string.find()`](http://docs.python.org/2/library/string.html) over `in` if you're not interested in the position of the character to match? As it is using regular expressions under water I guess this is slower too. – gertvdijk Jun 05 '13 at 09:10
  • Not true, http://wiki.python.org/moin/TimeComplexity time lookup of in over lists is O(n), same of str.find ; anyways I prefer to use "find" because I think it makes the code clearer, just personal preference – luke14free Jun 05 '13 at 09:14
0

If I understand it well, you wish to see all the entry starting with a given number ... but renumbered?

# 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

If you (or your teacher?) like one liners here is a shortcut:

>>> 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
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125