removing single notations and practices [] from list items in python - python

I have a list with a strange structure as follows:
List_input = [['statment01'], ['statment02'], ['statment03'],.....['statement1000']]
I need to remove the inner brackets [] and the single notations of each item.
The required output list is like this:
List_output = ["statment01", "statment02", "statment03",....., "statement1000"]
Could anyone help with this?

Just iterate over list and append it to new array.
List_output = []
for i in List_input:
List_output.append(i[0])

I hope this is what u r expecting:
def remove_nest(l):
for i in l:
if type(i) == list:
remove_nest(i)
else:
output.append(i)
l = [[1,2,3],[4,5,6],[6,7,8]]
output = []
print ('The given list: ', l)
remove_nest(l)
print ('The list after removing nesting: ', output)
OUTPUT:
The given list: [[1, 2, 3], [4, 5, 6], [6, 7, 8]]
The list after removing nesting: [1, 2, 3, 4, 5, 6, 6, 7, 8]

Related

How can I merge multiple unknown number of lists together?

Based on the number of time the for loop runs, I get multiple list. I want to merge all those list and make one list.
for example:
list = []
for i in item:
list.append(i)
print(list)
How can I merge all the list I get to one list ?
If your item is list of lists, then you can use extend to achieve the same.
lst = []
for i in item:
lst.append(i)
out = []
for sublist in lst:
out.extend(sublist)
print(out)
Also, avoid using python keywords like list for the variable name, use something like lst instead.
You should avoid using list as a variable name, it's a reserved word for python lists.
This code should work for you:
list_ = []
f_list = []
item = [1,2,3,4,5]
for i in item:
list_.append(i)
f_list.extend(list_)
print(list_)
print("Final list - ", f_list)
Output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Final list - [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]

create sub-list of order integers present in a list and store them in another nested list in python

I have an array list like this:
list = [1,2,3,4,9,1,12,9,8,7,8,9,10,12,16,1,2,3,4,5,6,7,8,9,10]
I want to create a sub-list from a list of ordered numbers (which are already in sequence in arr_list for e.g. 1,2,3,4 are already in order, similarly 7,8,9,10 and last 10 numbers)
Final output will look like this:
[[1,2,3,4],[7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
Tried comparing if the i'th element of first for loop is less than the j'th element of second for loop.
This is what i've tried:
sub_list=[]
for i in range(0,length_of_list):
for j in range(i+1,length_of_list):
if (arr_list[i] < arr_list[j]):
sub_list.append(arr_list[i])
else:
pass
New to python, any leads are much appreciated.
Try this...
res, temp = [], []
lst = [1,2,3,4,9,1,12,9,8,7,8,9,10,12,16,1,2,3,4,5,6,7,8,9,10]
for i in lst:
if (not temp) or (temp[-1] == i-1):
temp.append(i)
else:
res.append(temp)
temp = [i]
res.append(temp)
print([i for i in res if len(i)>1])
Outputs:
[[1, 2, 3, 4], [7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
tell me if its okay for you...

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]

how to combine same matching items in a 1d list and make it as 2d list [duplicate]

From this list:
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
I'm trying to create:
L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
Any value which is found to be the same is grouped into it's own sublist.
Here is my attempt so far, I'm thinking I should use a while loop?
global n
n = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted list
l = [] #Empty list to append values to
def compare(val):
""" This function receives index values
from the n list (n[0] etc) """
global valin
valin = val
global count
count = 0
for i in xrange(len(n)):
if valin == n[count]: # If the input value i.e. n[x] == n[iteration]
temp = valin, n[count]
l.append(temp) #append the values to a new list
count +=1
else:
count +=1
for x in xrange (len(n)):
compare(n[x]) #pass the n[x] to compare function
Use itertools.groupby:
from itertools import groupby
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
print([list(j) for i, j in groupby(N)])
Output:
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
Side note: Prevent from using global variable when you don't need to.
Someone mentions for N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1] it will get [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]
In other words, when numbers of the list isn't in order or it is a mess list, it's not available.
So I have better answer to solve this problem.
from collections import Counter
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
C = Counter(N)
print [ [k,]*v for k,v in C.items()]
You can use itertools.groupby along with a list comprehension
>>> l = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
>>> [list(v) for k,v in itertools.groupby(l)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
This can be assigned to the variable L as in
L = [list(v) for k,v in itertools.groupby(l)]
You're overcomplicating this.
What you want to do is: for each value, if it's the same as the last value, just append it to the list of last values; otherwise, create a new list. You can translate that English directly to Python:
new_list = []
for value in old_list:
if new_list and new_list[-1][0] == value:
new_list[-1].append(value)
else:
new_list.append([value])
There are even simpler ways to do this if you're willing to get a bit more abstract, e.g., by using the grouping functions in itertools. But this should be easy to understand.
If you really need to do this with a while loop, you can translate any for loop into a while loop like this:
for value in iterable:
do_stuff(value)
iterator = iter(iterable)
while True:
try:
value = next(iterator)
except StopIteration:
break
do_stuff(value)
Or, if you know the iterable is a sequence, you can use a slightly simpler while loop:
index = 0
while index < len(sequence):
value = sequence[index]
do_stuff(value)
index += 1
But both of these make your code less readable, less Pythonic, more complicated, less efficient, easier to get wrong, etc.
You can do that using numpy too:
import numpy as np
N = np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
counter = np.arange(1, np.alen(N))
L = np.split(N, counter[N[1:]!=N[:-1]])
The advantage of this method is when you have another list which is related to N and you want to split it in the same way.
Another slightly different solution that doesn't rely on itertools:
#!/usr/bin/env python
def group(items):
"""
groups a sorted list of integers into sublists based on the integer key
"""
if len(items) == 0:
return []
grouped_items = []
prev_item, rest_items = items[0], items[1:]
subgroup = [prev_item]
for item in rest_items:
if item != prev_item:
grouped_items.append(subgroup)
subgroup = []
subgroup.append(item)
prev_item = item
grouped_items.append(subgroup)
return grouped_items
print group([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
# [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

split list into sublists [duplicate]

This question already has answers here:
Loop "Forgets" to Remove Some Items [duplicate]
(10 answers)
Closed 8 years ago.
Define a function split_list that takes in a list of numbers and a number a and splits it into two sublists: list1 that contains numbers smaller than or equal to a, and another list, list2 containing numbers greater than a. list1 and list2 must be returned as elements of a tuple.
My code:
def split_list(lst, a):
list1 = []
list2 = []
for i in lst:
if i <= a:
list1.append(i)
lst.remove(i)
elif i > a:
list2.append(i)
lst.remove(i)
return (list1, list2)
Test code:
split_list([1, 10, 4, 9, 7, 2, 5, 8, 3, 4, 9, 6, 2], 5)
should give: ([1, 4, 2, 5, 3, 4, 2], [10, 9, 7, 8, 9, 6])
But I got ([1, 4, 5, 3, 2], [7, 9]) instead. Whats wrong with my code?
As commented by Martijn, you're breaking your list lst by trying to iterate through it and remove from it at the same time.
You don't need to remove from lst, so you can remove those lines.
Or, you could iterate over a copy of lst, whilst removing from the original lst.
To do this, simply change your for loop to be:
for i in lst[:]
This will copy a slice corresponding to the whole of lst for you to iterate over.
To avoid skipping elements you can alternatively loop through the list backwards deleting as you go. Here's an example using list indexes instead of the "for listitem in list" construct.
def split_list(lst, a):
list1 = []
list2 = []
for x in range(len(lst)-1,-1,-1):
if lst[x] <= a:
list1.append(lst[x])
del lst[x]
elif lst[x] > a:
list2.append(lst[x])
del lst[x]
return (list1, list2)
print split_list([1, 10, 4, 9, 7, 2, 5, 8, 3, 4, 9, 6, 2], 5)
# outputs ([2, 4, 3, 5, 2, 4, 1], [6, 9, 8, 7, 9, 10])
Modifying a list while iterating over it is always going to end badly. I would do instead:
for i in lst[:]: # Make a shallow copy.
#stuff
We are then iterating over that unmodified copy, so based on this we can edit the original safely.
Or just don't modify the list at all, meaning you can remove all uses of lst.remove(i) which should also fix the problem.
def split_list(lst, a):
list1 = []
list2 = []
for i in lst:
if i <= a:
list1.append(i)
elif i > a:
list2.append(i)
return (list1, list2)
There's no need to remove the items from the lst list as you iterate through it.

Categories