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

3
  • 1
    You seem to be describing and showing different things. Did you mean to output one string for each number? Commented Jun 5, 2013 at 8:53
  • what if a contains : '21 is the population'? Commented Jun 5, 2013 at 8: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'), } Commented Jun 5, 2013 at 12:44

6 Answers 6

3
for i in a:
    if "1" in i:
        print(i)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

2 Comments

What is the advantage of string.find() 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.
Not true, 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
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])

Comments

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

Comments

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?

5 Comments

startswith seems a little bit to restriced for how the question is worded.
@Tichodroma I shaped my response based on the example data. However, you are correct if the instructions are accurate. Ill update my response.
Also note that startswith is a lot slower than a[0]
@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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.