Splitting strings without resulting in 2-D list - python

How do I split strings in a list without resulting in a 2-D list?
list1:['Ben&Jerry', 'Julia', 'Sally&Don', 'Tom', 'Tracy&Jim']
to output:
['Ben','Jerry','Julia','Sally', 'Don','Tom','Tracy','Jim']
using
flat_list=[s.split('&') if "&" in s else s for s in list1 ]
will give me a 2-D list.

Lazy way:
flat_list = '&'.join(list1).split('&')

This should work
[i for j in [i.split('&') for i in list1] for i in j]

Related

coverting list of string coordinates into list of coordinates without string

I have a list
flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8']
How can I convert it into
[[53295,-46564.2], [53522.6,-46528.4], [54792.9,-46184], [55258.7,-46512.9], [55429.4,-48356.9], [53714.5,-50762.8]]
I tried
l = [i.strip("'") for i in flat_list]
nothing works.
l = [i.strip("'") for i in flat_list]
coords = [map(float,i.split(",")) for i in flat_list]
print(coords)
gives me <map object at 0x7f7a7715d2b0>
Why complicate things?
Without any builtins such as map and itertools, this approach with a nested list comprehension should be a relatively simple and efficient one.
flat_list = ['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9',
'53714.5,-50762.8']
result = [float(f) for pair in flat_list for f in pair.split(',')]
print(result)
Output:
[53295.0, -46564.2, 53522.6, -46528.4, 54792.9, -46184.0, 55258.7, -46512.9, 55429.4, -48356.9, 53714.5, -50762.8]
To instead end up with a list of lists, you can change the order of the for statements and then add braces around the sub-list for each str.split result, as shown below:
flat_list = ['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9',
'53714.5,-50762.8']
result = [[float(f) for f in pair.split(',')] for pair in flat_list]
print(result)
Output:
[[53295.0, -46564.2], [53522.6, -46528.4], [54792.9, -46184.0], [55258.7, -46512.9], [55429.4, -48356.9], [53714.5, -50762.8]]
Edit after your comment: to get a list of lists you can use
list2 = [[float(f) for f in el.split(",")] for el in flat_list]
or
list2 = [list(map(float,el.split(","))) for el in flat_list]
Deprecated: If you are okay with 2 operations instead of a one-liner, go with:
list2 = map(lambda el: el.split(","), flat_list)
list3 = [float(el) for sublist in list2 for el in sublist]
or
import itertools
list2 = map(lambda el: el.split(","), flat_list)
list3 = list(map(float, itertools.chain.from_iterable(list2)))
I see that the coordinates come in pairs, so in order to convert them to an integer or float first we need to split them so they become single numbers.
flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8']
coordinates = []
for pair in flat_list:
coordinates.extend(pair.split(','))
result = [float(x) for x in coordinates]
This is not the shortest way to do it, but I think it does the job.

Comparing two lists with specific values to read

I have two lists
list1 = ['01:15', 'abc', '01:15', 'def', '01:45', 'ghi' ]
list2 = ['01:15', 'abc', '01:15', 'uvz', '01:45', 'ghi' ]
and when I loop through the list
list_difference = []
for item in list1:
if item not in list2:
list_difference.append(item)
and I managed to get the difference, but I need time as well
because it is a separate item and 'uvz' does not mean to me anything in the list with a few thousand entries.
I tried to convert it to the dictionary, but it overwrites with the last key:value {'01:15' : 'def'}.
Convert the two lists to sets of tuples, then use the set difference operator.
set1 = set((list1[i], list1[i+1]) for i in range(0, len(list1), 2))
set2 = set((list2[i], list2[i+1]) for i in range(0, len(list2), 2))
list_difference = list(set1 - set2)
reformat your data, then do whatever you have done before
list1=list(zip(list1[::2],list1[1::2]))
list2=list(zip(list2[::2],list2[1::2]))

how can i reverse a list as well as its string elements using python using nested for loops?

I have tried as below , it can be done using list comprehension [also without using in-build functions and techniques like [::-1] ], but want to do it using nested for loops as below ?
l=['temp','test']
l1=[]
for t in l:
for i in t:
l1.append(str(i[::-1]))
print(l1)
input: ['test','temp']
required output : ['pmet','tset']
In order to reverse the order of the elements in the list, you can use reverse:
for i in reversed(array):
print(i)
Or, you can use array.reverse().
in order to reverse each string, you can use [::-1], for example:
txt = "Hello World"[::-1]
print(txt)
output:
dlroW olleH
Looking at the code you added, you can do something like this:
l=['temp','test']
reverse_l=[]
reverse_l = [item[::-1] for item in l] # This is list comprehensions, you can read about it in the link at the end of the answer
reverse_l.reverse()
print(l)
print(reverse_l)
output:
['temp', 'test']
['tset', 'pmet']
A solution without list comprehension:
l=['temp','test']
reverse_l=[]
for item in l:
item = item[::-1]
reverse_l.append(item)
reverse_l.reverse()
print(l)
print(reverse_l)
You can find information about list Comprehensions in python here.
Using nested loops:
l=['temp','test']
print([''.join([w[i] for i in range(len(w)-1, -1, -1)]) for w in reversed(l)])
Output:
['pmet', 'tset']
try this
l=['temp','test']
l1=[]
for t in l:
l1.append(t[::-1])
print(l1)
You don't need a nested loop:
l = ['temp', 'test']
l1 = [
word[::-1]
for word in l
]
print(l1)
output:
['pmet', 'tset']
You can try the following :
input_list = ['test', 'temp']
input_list.reverse()
print(list(map(lambda x: x[::-1], input_list)))
for i in range(len(l)):
l[i] = l[i][::-1]
l = l[::-1]
you don't need nested loops for desired output you have given.

How to verify any of lists of strings are in another array and append the array in Python

I have an array of strings in Python:
array=array(['Thisis_anapple','Thatis_acat', 'Thoseare_dogs'], dtype=object)
I want to append all the strings that have 'cat' or 'dog'. Ideal result is:
list=['Thatis_acat','Thoseare_dogs']
My code is:
list=[]
if any(x in array for x in ['cat', 'dog']):
list=list.append(x)
print(list)
But the result is actually blank list.
A = ['Thisis_anapple','Thatis_acat', 'Thoseare_dogs']
L = ['cat', 'dog']
R = [entry for entry in A if any(l in entry for l in L)]
print(R)
This solution involves conditional list comprehension
It basically says make a list R, so that it includes every entry from A if any pattern from L can be found in that entry.
You can use re:
import re
array = ['Thisis_anapple','Thatis_acat', 'Thoseare_dogs']
words = ['cat', 'dog']
to_find = re.compile('|'.join(words))
result = list(filter(to_find.search, array))
This could be done using a list comprehension instead of using filter but it seemed more appropriate:
result = [s for s in array if to_find.search(s)]
Result: (same for both filter and list comp)
['Thatis_acat', 'Thoseare_dogs']

Splitting lists by empty element

I have a single list that could be any amount of elements.
['jeff','ham','boat','','my','name','hello']
How do I split this one list into two lists or any amount of lists depending on blank string elements?
All these lists can then be put into one list of lists.
If you are certain that there is only one blank string in the list, you can use str.index to find the index of the blank string, and then slice the list accordingly:
index = lst.index('')
[lst[:index], lst[index + 1:]]
If there could be more than one blank string in the list, you can use itertools.groupby like this:
lst = ['jeff','ham','boat','','my','name','hello','','hello','world']
from itertools import groupby
print([list(g) for k, g in groupby(lst, key=bool) if k])
This outputs:
[['jeff', 'ham', 'boat'], ['my', 'name', 'hello'], ['hello', 'world']]
Using itertools.groupby, you can do:
from itertools import groupby
lst = ['jeff','ham','boat','','my','name','hello']
[list(g) for k, g in groupby(lst, key=bool) if k]
# [['jeff', 'ham', 'boat'], ['my', 'name', 'hello']]
Using bool as grouping key function makes use of the fact that the empty string is the only non-truthy string.
This is one approach using a simple iteration.
Ex:
myList = ['jeff','ham','boat','','my','name','hello']
result = [[]]
for i in myList:
if not i:
result.append([])
else:
result[-1].append(i)
print(result)
Output:
[['jeff', 'ham', 'boat'], ['my', 'name', 'hello']]
Let list_string be your list. This should do the trick :
list_of_list=[[]]
for i in list_string:
if len(i)>0:
list_of_list[-1].append(i)
else:
list_of_list.append([])
Basically, you create a list of list, and you go through your original list of string, each time you encounter a word, you put it in the last list of your list of list, and each time you encounter '' , you create a new list in your list of list. The output for your example would be :
[['jeff','ham','boat'],['my','name','hello']]
i'm not sure that this is what you're trying to do, but try :
my_list = ['jeff','ham','boat','','my','name','','hello']
list_tmp = list(my_list)
final_list = []
while '' in list_tmp:
idx = list_tmp.index('')
final_list.append(list_tmp[:idx])
list_tmp = list_tmp[idx + 1:]

Categories

Resources