Unpack List with key value pair - python

I need to get the value(the right hand value after the colon) in this list
list = [apple:tuesday, banana:wednesday, guava:thursday]

first your list will be like
list1=["apple:tuesday", "banana:wednesday", "guava:thursday"]
k=0
for i in list1:
x=i.split(":")
print(x)
list1[k]=x[1]
k+=1
print(list1)
i hope this is what you were trying to do

you can do this by list comprehension.it's easy and fast
l = ["apple:tuesday", "banana:wednesday", "guava:thursday"]
new_l = [item.split(":")[1] for item in l]
list comprehension work like this
l = [i for i in range(5)]
# l = [0,1,2,3,4]

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.

how to transform a python list to a list of tuple in 1/2 lines?

Input: ['a','b','c','d','e']
Output: [('a','b'),('c','d'),('e')]
How can I do it in 1 or 2 lines of code ?
For the moment I have this:
def tuple_list(_list):
final_list = []
temp = []
for idx, bat in enumerate(_list):
temp.append(bat)
if idx%2 == 1:
final_list.append(temp)
temp = []
if len(temp) > 0: final_list.append(temp)
return final_list
tuple_list(['a','b','c','d','e'])
You can use list comprehension. First we will have a range with a step of 2. Using this we will take proper slices from the input list to get the desired result:
lst = ['a','b','c','d','e']
result = [tuple(lst[i:i+2]) for i in range(0, len(lst), 2)]
Try this list comprehension
x = ['a','b','c','d','e']
[(x[i],x[i+1]) for i in range(0,len(x)-1) if i%2==0]
You could create an iterator with the built in iter() function and pass that to the built zip() function.
l = ['a','b','c','d','e']
i = iter(l)
zip(i, i)
if you'd like to group by 3 you can pass it 3 times to zip()
zip(i, i, i)
x = ['a','b','c','d','e']
y = [tuple(x[i:i+2]) for i in range(0,len(x),2)]
You can slice the array by moving a sliding window of size 2 over your list.
range(start, end, step) helps you to move window by step(2 in your case) while slicing helps you create smaller list out of bigger list.
All that put into a list comprehension gives you a desired output.

How to remove item in list in list with list comprehension

I have a large list like this:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
I'm trying to remove all numbers within the lists of this list. So I made a list of numbers as strings from 1 to 100:
def integers(a, b):
return list(range(a, b+1))
numb = integers(1,100)
numbs = []
for i in range(len(numb)):
numbs.append(str(numb[i])) # strings
numbs = ['1','2',....'100']
How can I iterate through lists in mylist and remove the numbers in numbs? Can I use list comprehension in this case?
If number is always in the end in sublist
mylist = [ x[:-1] for x in mylist ]
mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick.
However, this isn't quite what you've asked. Nothing was actually removed from mylist, we've just built an entirely new list and reassigned it to mylist. Same logical result, though.
If numbers are always at the end and only once, you can remove the last item like:
my_new_list = [x[:-1] for x in mylist]
If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]
I would also recommend to generate the list of interger as follow :
integer_list = list(map(str, range(1, 100)))
I hope it helps :)
Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]
If you have the following list:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]
Using list comprehension to remove element in numbs
[[l for l in ls if l not in numbs] for ls in mylist]
This is a more general way to remove digit elements in a list
[[l for l in ls if not l.isdigit()] for ls in mylist]

Join sublist in a list in python when the sublists are still items in the big list

I have a list like this:
l = [[1,4], [3,6], [5,4]]
I want to join the inner list with ":". I want to have the result as:
l = ['1:4', '3:6', '5:4']
How can I achieve it with Python?
You can use list comprehension to achieve this:
[':'.join(map(str, x)) for x in l]
l = [[1,4], [3,6], [5,4]]
fl = []
for x in l:
fl.append(str(x[0])+':'+str(x[1]))
print(fl) # Final List, also you can do: l = fl
But, i think that you want to do dictionaries, if this is true, you have to do:
l = [[1,4], [3,6], [5,4]]
fd = {}
for x in l:
fd[x[0]] = x[1]
print(fd) # Final Dictionary
EXPLANATION:
l = [[1,4], [3,6], [5,4]] # Your list
fl = [] # New list (here will be the result)
for x in l: # For each item in the list l:
fl.append(str(x[0])+':'+str(x[1])) # Append the first part [0] of this item with ':' and the second part [1].
print(fl)
With Dictionaries:
l = [[1,4], [3,6], [5,4]] # Your list
fd = {} # New dictionary
for x in l: # For each item in the list l:
fd[x[0]] = x[1] # Make a key called with the first part of the item and a value with the second part.
print(fd) # Final Dictionary
Also you can make a dictionary easier:
l = [[1,4], [3,6], [5,4]]
l = dict(l) # Make a dictionary with every sublist of the list (it also works with tuples), the first part of the sublist is the key, and the second the value.
You can do:
final_list = []
for i in l:
a = str(i[0])+':'+str(i[1])
final_list.append(a)
print(final_list)

Nested lists python

Can anyone tell me how can I call for indexes in a nested list?
Generally I just write:
for i in range (list)
but what if I have a list with nested lists as below:
Nlist = [[2,2,2],[3,3,3],[4,4,4]...]
and I want to go through the indexes of each one separately?
If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
for index2 in xrange(len(l[index1])):
print index1, index2, l[index1][index2]
But it is more pythonic to iterate through the list itself:
for inner_l in l:
for item in inner_l:
print item
If you really need the indices you can also use enumerate:
for index1, inner_l in enumerate(l):
for index2, item in enumerate(inner_l):
print index1, index2, item, l[index1][index2]
Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]
To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.
You can do this. Adapt it to your situation:
for l in Nlist:
for item in l:
print item
The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
Example:
input -> [1,2,[3,4]]
output -> [1,2,3,4]
The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
if l is not None:
e = l[0]
if isinstance(e, list):
get_elements_from_nested_list(e, new_l)
else:
new_l.append(e)
if len(l) > 1:
return get_elements_from_nested_list(l[1:], new_l)
else:
return new_l
Call of the method
l = [1,2,[3,4]]
new_l = []
get_elements_from_nested_list(l, new_l)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for numbers2 in numbers:
results.append(numbers2)
return results
print flatten(n)
Output: n = [1,2,3,4,5,6,7,8,9]
I think you want to access list values and their indices simultaneously and separately:
l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
for j in range(l_item_len):
print(f'List[{i}][{j}] : {l[i][j]}' )

Categories

Resources