Python: Inline if to print non-empty strings? - python

I'm trying to print out just the non-empty strings in a list. I can't seem to get the below to work, what am I doing wrong??
print item in mylist if item is not ""

The following is invalid syntax: print item in mylist if item is not ""
You could perhaps achieve what you want using a list comprehension:
>>> mylist = ["foo","bar","","baz"]
>>> print [item for item in mylist if item]
['foo', 'bar', 'baz']

You could create a generator to grab the items in the list that are not empty.
nonempties = (item for item in mylist if item)
Then loop and print or join them into a string.
print ' '.join(nonempties)

The filter() built-in is well suited for exactly that, just pass None instead of a function:
>>> filter(None, ['Abc', '', 'def', None, 'ghi', False, 'jkl'])
['Abc', 'def', 'ghi', 'jkl']
Details at http://docs.python.org/library/functions.html

Related

How do I split strings from a list and store them to another list?

I am trying to split the strings from a list based on the whitespaces.
My code:
line=['abc def','ghi jk']
for x in line:
word=x.split(' ')
print(word)
Expected output:
['abc','def','ghi','jk']
But I keep getting the output as:
['ghi','jk']
Where am I going wrong?
You can join the strings with a space first before splitting the string by spaces:
' '.join(line).split()
This returns:
['abc', 'def', 'ghi', 'jk']
Every time word=x.split(' ') runs, the previous value of words is replaced by a new value. In your case, the first iteration of the loop creates word = ['abc','def'], and the second iteration replaces it by word = ['ghi','jk'].
You need to store the result of each iteration into a new list:
line = ['abc def', 'ghi jk']
result = []
for x in line:
result.extend(x.split(' '))
print(result)
A neat one-liner:
Given line = ['abc def', 'ghi jk']
word = [item for sublist in [elem.split() for elem in line] for item in sublist]
Then you have
>>> word
['abc', 'def', 'ghi', 'jk']
What happens here? The [elem.split() for elem in line] is a list-comprehension, taking elem.split() for each element in the original list line, and putting each result in a list.
>>> [elem.split() for elem in line]
[['abc', 'def'], ['ghi', 'jk']]
Suppose then, that we again use list-comprehension and take from each element of our new nested list, each element it has, and puts it in a list. The procedure is called flattening of a list, and is of the form:
flattened_list = [item for sublist in nestedlists for item in sublist]
Split it, then flatten
line = ['abc def','ghi jk']
temp = [s.split(' ') for s in line]
res = [c for s in temp for c in s]
print(res)
Result
['abc','def','ghi','jk']
Or by using operator and reduce
import operator
from functools import reduce
line = [s.split(' ') for s in line]
res = reduce(operator.concat, line)
print(res)
Result:
['abc', 'def', 'ghi', 'jk']

Create a new list by comparing values in a list and string

I have elements in a predefined list and a query string. I would like to check if the query_str has any values in the predefined list and if so, append them to a new list as separate elements.
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
I have the syntax to compare the string to the values in the list, but I can't get the values that appear in the string to append to the new list as individual elements in the list.
In the example above, new_lst should be new_lst = ['hello', 'see you later'].
What I have now just results in True when I print new_lst.
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
match = if any(string in query_str for string in predefined_lst)
new_lst.append(match)
print(new_lst)
You've got lost in the list comprehension:
new_lst = [string for string in predefined_lst if string in query_str]
Currently you are appending a True or False value to new_lst in your line,
match = if any(string in query_str for string in predefined_lst)
This is because if ... returns the boolean True or False.
Instead, try this
for x in predefined_list:
if x in query_str:
new_list.append(x)
Or as a list comp,
new_lst = [string for string in predefined_lst if string in query_str]
Another way, using filter:
>>> predefined_lst = ['hello', 'goodbye', 'see you later']
>>> query_str = 'hello | are you having a nice day? see you later |'
>>>
>>> list(filter(lambda s: s in query_str, predefined_lst))
['hello', 'see you later']
This is a simple solution:
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
for item in predefined_lst:
if item in query_str:
new_lst.append(item)
print(new_lst)
You could use re.split to parse out by various delimiters:
[i.strip() for i in re.split(r'[?|]',query_str) if i.strip() in predefined_lst]
Or:
[i for i in re.split(r'(\s+)?[?|](\s+)?',query_str) if i in predefined_lst]
You are appending the result of comparison to new_list. What you should be appending is the string itself.
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
for str in predefined_lst:
if(str in query_str):
new_lst.append(str)
print new_lst

List of strings in a list

I have multiple lists of strings, inside a list. I want to change the strings that are digits into integers.
ex:-
L1=[['123','string','list']['words','python','456']['code','678','links']]
What i want is:
[[123,'string','list']['words','python',456]['code',678,'links']]
I have tried using-
W=range(len(L1))
Q=range(2)
if (L1[W][Q]).isdigit():
(L1[W][Q])=(int(L1[W][Q]))
when I tried the above code, I got an error.
Use str.isdigit():
L1=[['123','string','list'],['words','python','456'],['code','678','links']]
for item in L1:
for i in range(0,len(item)):
if(item[i].isdigit()):
item[i] = int(item[i])
print(L1)
Something like this:
>>> mylist = [['123','string','list'], ['words','python','456'], ['code','678','links']]
>>> [ [(int(item) if item.isdigit() else item) for item in sublist] for sublist in mylist]
[[123, 'string', 'list'], ['words', 'python', 456], ['code', 678, 'links']]

Convert certain values in list to int

I have a list of lists and I want to convert the second value in each list to an int since it is currently a string
[['hello','how','are','you','1'],['hello','how','are','you','2']]
I am trying to convert index 4 to an int in each list within this larger list but when I do
for hi in above:
int(hi[4])
It is just returning the int when I print the list and not the entire list.
Just traverse it and convert it using the int() function for every 4th element in every list inside :
for li in my_list:
li[4] = int(li[4])
This list comprehension is one way to do it:
a_list = [[int(a) if item.index(a) == 4 else a for a in item] for item in a_list]
Demo:
>>> a_list = [['hello','how','are','you','1'],['hello','how','are','you','2']]
>>> a_list = [[int(a) if item.index(a) == 4 else a for a in item] for item in a_list]
>>> a_list
[['hello', 'how', 'are', 'you', 1], ['hello', 'how', 'are', 'you', 2]]
>>>

Index of \n in Python list

Okay, here I have another problem, I need to find position of \n alone in my list.
list = ['abc', '\n', 'def', 'ghi', '\n', 'jkl']
So, I need to get the position of all '\n' entries from this list.
I used
a=list.index('\n')
but got only one value as '1'. How to get both positions?
e.g. I will get a list with the position of '\n'
position = ['1', '4']
'1' represents first position of \n in list and the '4' represents second at the fourth place in list.
You'll need to iterate over the elements. This can be easily done by using a list comprehension and enumerate for the indexes:
indexes = [i for i, val in enumerate(list) if val == '\n']
Demo:
>>> lst = ['abc', '\n', 'def', 'ghi', '\n', 'jkl']
>>> [i for i, val in enumerate(lst) if val == '\n']
[1, 4]
[i for i, x in enumerate(l) if x == "\n"]
# => [1, 4]
And don't call a list list since this is a builtin function.
To find indices of an item in a list with multiple occurrences, following code should work
print [i for i in range(len(list)) if list[i] == '\n']
Here I have used list as it was taken in your question but do not use keywords as variables .

Categories