How to split string based on position in string - python

Given the following text:
input_value= """12
23
54"""
I want to return lists with the first and second elements of each line:
[[1,2,5], [2,3,4]]
I am trying to achieve this using a one-liner but struggling to access the correct indexes of each line and then placing them into a separate list. The number of returned lists should be equal to the number of digits present on each line:
I've tried the following as a base but clearly requires more logic in order to retrieve the correct digits:
new_list = [[elem] for elem in input_value.split('\n')]

Use a nested list comprehension:
out = [[int(i) for i in x] for x in zip(*input_value.split('\n'))]
Output:
[[1, 2, 5], [2, 3, 4]]

input_value= """12
23
54
"""
lst1 = []
lst2 = []
for i in input_value.splitlines():
if i:
lst1.append(int(i[0]))
lst2.append(int(i[1]))
lst = [lst1, lst2]
print(lst)
See if this works.

You could use something like
[[*elems] for elems in zip(*input_value.split("\n"))]
EDIT:
To create a list of integers, use
[[*map(int, elems)] for elems in zip(*input_value.split("\n"))]

Another possible solution:
[[list(map(int,x))[y] for x in input_value.split()] for y in range(2)]
Output:
[[1, 2, 5], [2, 3, 4]]

Related

Filter nested list with list comprehension based on other list in python

I have two lists like this:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
I would now like to filter list a, to keep only the items which contain the items in list b. So the desired output would look like this:
[[1,2,3],[2,3,4]]
I have tried some nested list comprehensions, which I could think of, but could not get the desired output. Any advice is appreciated.
you could try something like this :
print([i for i in a if any(map(i.__contains__,b))])
>>> [[1, 2, 3], [2, 3, 4]]
I would try something like this:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
result = [lst for lst in a if any(x in lst for x in b)]
A combination of list comprehension and sets would yield the wanted result. Note; I assume that repeated items and ordering is not of interest, if this is the case - a set won't work since it ignores ordering and only allows unique items.
A simple list comprehension would do, like below
filter_items = set(filter_items)
[sublist for sublist in original_list if not set(sublist).isdisjoint(filter_items)]
There's mainly one interesting part of this list comprehension, namely the if not set(sublist).isdisjoint(filter_items). Here you only keep the sublist if the set of sublist is not disjoint of the set filter_items i.e. none of the filter_items is in the sublist.
for your given example the provided answer would yield the following:
>>> a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
>>> b = set([1,2])
>>> [sublist for sublist in a if not set(sublist).isdisjoint(b)]
[[1, 2, 3], [2, 3, 4]]
Using a set approach the in can be mimic with an intersection:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
b_as_set = set(b)
out = [l for l in a if b_as_set.intersection(l)]
# [[1, 2, 3], [2, 3, 4]]
I would try something like this.
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
print([lst for lst in a if any([item in b for item in lst])])

Add two lists which return a list the addition of the adjacent element

I want to write a function add_list, which adds two lists adjacent elements.
E.g. l1 = [1, 2, 3], l2= [1,2,3] should give [2,4,6]. I am lost and not sure how to approach it using loops. Can someone help please?
You can iterate both the lists using zip and then use list comprehension on them
[x+y for x,y in zip(l1, l2)]
Sample run:
>>l1 = [1, 2, 3]
>>l2= [1,2,3]
>>[x+y for x,y in zip(l1, l2)]
[2, 4, 6]
Other possible solution is to iterate through the index (can be used in list comprehension as well)
result = []
for i in range(len(l1)):
result.append(l1[i] + l2[i])
Output:
>>result
[2, 4, 6]
The following code will add numbers in two given list provided that both have same number of elements
def add_list(a, b):
result = [] # empty list
# loop through all the elements of the list
for i in range(len(a)):
# insert addition into results
result.append(a[i] + b[i])
return result
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(add_list(l1, l2))

Python: how to remove single quote on first and last element of list

i have a list that goes like this ['1,2'] and i need to turn it into [1, 2]. Using int() won't work. Is there a way to add a single quote and then use int(), a way to remove a single quote or is there just a better way to do this?
here is the code that i am using
a_list = genres_selected.split()
map_object = map(int, a_list)
genres_selected_use = list(map_object)
genres_selected will always be different as it is being passed through ajax form
but here it is "1, 2"
I think you are looking to remove the string and convert it into an integer. Since the list has a string, you want to split the string using comma delimiter.
list_vals = ['1,2,3,4,5,6']
map_object = map(int, list_vals[0].split(','))
print (list(map_object))
The output of this will be:
[1, 2, 3, 4, 5, 6]
However, if your list has multiple strings of integers in single quotes, you can do:
my_list = ['1,2','3,4','5,6']
num_list = [[int(i) for i in num.split(',')] for num in my_list]
print (num_list)
The output of this will be:
[[1, 2], [3, 4], [5, 6]]
lst = ['1,2', '3,4,5']
new_list = []
for item in lst:
new_list.extend([int(num) for num in item.strip().split(',')])
print(new_list)
>>> [1, 2, 3, 4, 5]
One Liner Version
lst = ['1,2', '3,4,5']
print([int(item) for sublist in map(lambda item: item.split(','), lst) for item in sublist])
>>> [1, 2, 3, 4, 5]

Get element from list of list based on index from another list

I would like to retrieve specific elements within a list of lists without using list comprehension, loops, or any iterative approach in Python.
For example, given this list:
[[1,2,3,4],[3,4],[5,6,7]]
and this vector:
[0,0,1]
I would like to retrieve the 0th element on the 0th list, the 0th element of the 1st list, and the 1st element of the 2nd list:
[1,2,3,4][0] -> 1
[3,4][0] -> 3
[5,6,7][1] -> 6
Which should give this result:
[1,3,6]
Is this possible in python?
This is an alternate:
x = [[1,2,3,4],[3,4],[5,6,7]]
y = [0,0,1]
res = []
for i in range(len(x)):
res.append(x[i][y[i]])
Using a list comprehension with zip() is one of the most Pythonic way to achieve this:
>>> my_list = [[1,2,3,4],[3,4],[5,6,7]]
>>> my_vector = [0,0,1]
>>> [x[i] for x, i in zip(my_list, my_vector)]
[1, 3, 6]
However, since OP can not use list comprehension, here's an alternative using map() with lambda expression as:
>>> list(map(lambda x, y: x[y], my_list, my_vector))
[1, 3, 6]
In the above solution, I am explicitly type-casting the object returned by map() to list as they return the iterator. If you are fine with using iterator, there's no need to type-cast.
you can use zip
l = [[1,2,3,4],[3,4],[5,6,7]]
i = [0,0,1]
op = []
for index, element in zip(i, l):
op.append(element[index])
output
[1, 3, 6]
using map you can do this way
a = [[1,2,3,4],[3,4],[5,6,7]]
b = [0, 0, 1]
result = list(map(lambda x,y: x[y], a,b))
print(result)
output
[1, 3, 6]

Turning a list into nested lists in python

Possible Duplicate:
How can I turn a list into an array in python?
How can I turn a list such as:
data_list = [0,1,2,3,4,5,6,7,8]
into a list of lists such as:
new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]
ie I want to group ordered elements in a list and keep them in an ordered list. How can I do this?
Thanks
This groups each 3 elements in the order they appear:
new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]
Give us a better example if it is not what you want.
This assumes that data_list has a length that is a multiple of three
i=0
new_list=[]
while i<len(data_list):
new_list.append(data_list[i:i+3])
i+=3
Something like:
map (lambda x: data_list[3*x:(x+1)*3], range (3))
Based on the answer from Fred Foo, if you're already using numpy, you may use reshape to get a 2d array without copying the data:
import numpy
new_list = numpy.array(data_list).reshape(-1, 3)
new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]
List comprehensions for the win :)
The following function expands the original context to include any desired list of lists structure:
def gen_list_of_lists(original_list, new_structure):
assert len(original_list) == sum(new_structure), \
"The number of elements in the original list and desired structure don't match"
list_of_lists = [[original_list[i + sum(new_structure[:j])] for i in range(new_structure[j])] \
for j in range(len(new_structure))]
return list_of_lists
Using the above:
data_list = [0,1,2,3,4,5,6,7,8]
new_list = gen_list_of_lists(original_list=data_list, new_structure=[3,3,3])
# The original desired outcome of [[0,1,2], [3,4,5], [6,7,8]]
new_list = gen_list_of_lists(original_list=data_list, new_structure=[2,3,3,1])
# [[0, 1], [2, 3, 4], [5, 6, 7], [8]]
The below one is more optimized and quite straightforward.
data_list = [0,1,2,3,4,5,6,7,8]
result =[]
i=0
while i <(len(data_list)-2):
result.append(data_list[i:i+3])
i+=3
print(result)
**output**
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Here is a generalized solution
import math
data_list = [0,1,2,3,4,5,6,7,8]
batch_size=3
n_batches=math.ceil(len(data_list)/batch_size)
[data_list[x*batch_size:min(x*batch_size+batch_size,len(data_list))]
for x in range(n_batches)]
It works even if the last sublist is not the same size as the rest (<batch_size)
Do you have any sort of selection criteria from your original list?
Python does allow you to do this:
new_list = []
new_list.append(data_list[:3])
new_list.append(data_list[3:6])
new_list.append(data_list[6:])
print new_list
# Output: [ [0,1,2] , [3,4,5] , [6,7,8] ]

Categories