How to split a list of lists - python

So I want to split a list of lists.
the code is
myList = [['Sam has an apple,5,May 5'],['Amy has a pie,6,Mar 3'],['Yoo has a Football, 5 ,April 3']]
I tried use this:
for i in mylist:
i.split(",")
But it keeps give me error message
I want to get:
["Amy has a pie" , "6" , "Mar 3"] THis kinds of format

Here's how you do it. I used an inline for loop to iterate through each item and split them by comma.
myList = [item[0].split(",") for item in myList]
print(myList)
OR You can enumerate to iterate through the list normally, renaming items as you go:
for index, item in enumerate(myList):
myList[index] = myList[index][0].split(",")
print(myList)
OR You can create a new list as you iterate through with the improved value:
newList = []
for item in myList:
newList.append(item[0].split(","))
print(newList)

Split each string in sublist :)
new = []
for l in myList:
new.append([x.split(',') for x in l])
print new

It's because it's a list of lists. Your code is trying to split the sub-list, not a string. Simply:
for i in mylist:
i[0].split(",")

Another way would be:
list(map(lambda x: x[0].split(","), myList))

Related

How to remove the '' (empty string) in the list of list in python?

I want to remove the empty string ('') in the list of list in python.
My input is
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
My expected output should be like :
final_list=[['country'],['India']]
I am new to python i just to tried this (Note* below tried code is not intended)
final=[]
for value in final_list:
if len(set(value))==1:
print(set(value))
if list(set(value))[0]=='':
continue
else:
final.append(value)
else:
(final.append(value)
print(final)
Can some one help on me achieve the expected output? in the generic way.
You can use a list comprehension to check if any values exist within the sub list, and a nested comprehension to only retrieve those that have a value
[[x for x in sub if x] for sub in final_list if any(sub)]
Try the below
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)
output
[['country'], ['India']]
You can use a nested list comprehension with any that checks if list contains at least one string not empty:
>>> [[j for j in i if j] for i in final_list if any(i)]
[['country'], ['India']]
Assuming the strings inside the list of list doesn't contain , then
outlist = [','.join(innerlist).split(',') for innerlist in final_list]
But if the strings in the list of list can contain , then
outlist = []
for inlist in final_list:
outlist.append(s for s in inlist if s != '')
You could do the following (Using my module sbNative -> python -m pip install sbNative)
from sbNative.runtimetools import safeIter
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
for sub_list in safeIter(final_list):
while '' in sub_list: ## removing empty strings from the sub list until there are no left
sub_list.remove('')
if len(sub_list) == 0: ## checking and removing lists in case they are empty
final_list.remove(sub_list)
print(final_list)
Use a list comprehension to find all sublists that contain any value. Then use a filter to get all entries in this sublist that contain a value (here checked with bool).
final_list = [list(filter(bool, sublist)) for sublist in final_list if any(sublist)]

Easier way to check if an item from one list of tuples doesn't exist in another list of tuples in python

I have two lists of tuples, say,
list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
Expected output: 'item4' # Item that doesn't exist in list2
As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?
Assuming your tuple structure is exactly as shown above, this would work:
tuple(set(x[0] for x in list1) - set(x[0] for x in list2))
or per #don't talk just code, better as set comprehensions:
tuple({x[0] for x in list1} - {x[0] for x in list2})
result:
('item4',)
This gives you {'item4'}:
next(zip(*list1)) - dict(list2).keys()
The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').
The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.
Try it online!
This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.
list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []
OutputTuple = [(a) for a, b in list2]
for i in list1:
if i in OutputTuple:
pass
else:
not_in_tuple.append(i)
for i in not_in_tuple:
print(i)
You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:
items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))
Output:
>>> list3
[('item4',)]
Try set.difference:
>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>>
Or even better:
>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>>
that is a difference operation for sets:
set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)
output:
{'item4'}
for i in list1:
a=i[0]
for j in list2:
b=j[0]
if a==b:
break
else:
print(a)

Replace string in specific index in list of lists python

How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:
mylist = [["test_one", "test_two"], ["test_one", "test_two"]]
i want to change the word "test" to "my" so the result would be only affecting the second index:
mylist = [["test_one", "my_two"], ["test_one", "my_two"]]
I can figure out how to change both of list but i can't figure out what I'm supposed to do if only change one specific index.
Use indexing:
newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)
Or oneliner if you always have two elements in the sublist:
newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)
Output:
[['test_one', 'my_two'], ['test_one', 'my_two']]
There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.
for two_word_list in mylist:
two_word_list[1] = two_word_list.replace("test", "my")

Extract substrings from a list into a list in Python

I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])

Adding a value to a list of lists

I want to add a value to a list of lists.
For input of [[1,2],[2,3]]
I want output of [[2,3],[3,4]]
I can do it with loops:
list_of_lists = [[1,2],[2,3]]
output = []
for list in list_of_lists:
sub_output = []
for value in list:
sub_output.append(value+1)
output.append(sub_output)
print(output)
Can I do this with list comprehension?
If I do:
[value + 1 for list in list_of_lists for value in list]
It gives me [2,3,3,4]. Can I get it to keep the sublist format somehow?
Try...
[ [n + 1 for n in inner_list] for inner_list in list ]
Yeah, you need a nested comprehension:
[[item + 1 for item in list] for list in list_of_lists]
Another way would be to use map:
map(lambda l: map(lambda i: i + 1, l), list_of_lists)
You need to nest a comprehension into that comprehension. Unpack each sublist to make it easier.
[[a+1, b+1] for a,b in list_of_lists]

Categories