Print mixed list without brackets in a single row [duplicate] - python

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 4 years ago.
I have a list in Python.
I have tried to set print(*arr, sep=",") refer "Print list without brackets in a single row". But my real problem is:
### List
num = 2
arr= [0, "txt", 4, 5, [3,4, num]]
# print full
print(arr)
# print an arr without brackets
print(*arr, sep=",")
Expected result:
0,txt,4,5,3, 4, 2
Actual result:
0,txt,4,5,[3, 4, 2]
The compiler does not remove brackets from sub-list. Please give me advice to fix it. Thanks!

Use a function to flatten the list first, and then print the new list.
def flatten(original, iterables=[list]):
out = []
for val in original:
if type(val) not in iterables:
out.append(val)
else:
out += flatten(val)
return out
print(flatten(arr))
Here I explicitly specify type(val) != list so that it will not attempt to split up your strings, but will flatten sub lists. Additionally, this method will handle nested lists of any depth.
Result:
>>> print(flatten(arr))
[0, 'txt', 4, 5, 3, 4, 2]
You can also pass a second argument iterables, which is a list containing what iterable types you wish to flatten. This can include list, tuple, or anything else. Here I default to list since that's what your example requires.

try this for removing nested bracket only from the list:
num = 2
arr = [0, "txt", 4, 5, [3,4, num]]
output = []
def removeBracket(arr):
for i in arr:
if type(i) == list:
removeBracket(i)
else:
output.append(i)
removeBracket(arr)
print(output) # [0, 'txt', 4, 5, 3, 4, 2]

Related

How to make a flat list from nested lists? [duplicate]

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 6 months ago.
Given a nested list of integers, implement an iterator to flatten it. Each
element is either an integer, or a list -- whose elements may also be integers
or other lists. For example, if the input is [[1,1],2,[1,1]], then the output
is [1, 1, 2, 1, 1]. If the input is [1,[4,[6]]], then the output is [1, 4, 6].
Would anyone be able to advise me as to where the code below went wrong?
I am just starting out with python.
def eb34(list1):
flat_list = []
for i in range(len(list1)):
if type(list[i]) == list:
flat_list += flatten(list1[i])
else:
flat_list.append(list1[i])
return flat_list
You can use recursion:
def flatten(arg):
if not isinstance(arg, list): # if not list
return [arg]
return [x for sub in arg for x in flatten(sub)] # recurse and collect
print(flatten([[1,1],2,[1,1]])) # [1, 1, 2, 1, 1]
print(flatten([1,[4,[6]]])) # [1, 4, 6]
Or to make a generator,
def flatten(arg):
if not isinstance(arg, list): # if not list
yield arg
else:
for sub in arg:
yield from flatten(sub)
print(*flatten([[1,1],2,[1,1]])) # 1 1 2 1 1
print(*flatten([1,[4,[6]]])) # 1 4 6
I don't know from where you are calling flatten() in your code. I am giving you a solution with the other information you have given.
def eb34(list1):
flat_list = []
for i in list1:
if isinstance(i, list):
for j in eb34(i):
flat_list.append(j)
else:
flat_list.append(i)
return flat_list
You can recursively flatten it:
def flatten_recursively(lst_in):
lst_out = []
for i in lst_in:
if type(i) == list:
for j in flatten_recursively(i):
lst_out.append(j)
else:
lst_out.append(i)
return lst_out
Also check out this answer, although you might have to adjust it to Python 3+: https://stackoverflow.com/a/10824420/18189622
The easiest way to make a flat list from nested lists is to use the itertools module. The itertools module has a function called chain that takes a list of lists and returns a single list.
>>> import itertools
>>> nested_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flat_list = list(itertools.chain(*nested_lists))
>>> flat_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Is there a function to convert a int list to a list that shows the smallest-to-largest order of the list? [duplicate]

This question already has answers here:
Sorting list based on values from another list
(20 answers)
Closed 3 years ago.
I need a function that turns a list like
[10,5,2,3,7]
to a list like
[4,2,0,1,3]
Basically a list [0,1,2,3,4...] but arranged in the order that the original list has, smallest to biggest.
I have no idea where to even start on a function like this. I have Python 3.5.2.
hiro protagonist's answer was close, but he indexed the wrong list.
>>> data = [10,5,2,3,7]
>>> sorted_list = sorted(data)
>>> [sorted_list.index(item) for item in data]
[4, 2, 0, 1, 3]
This wouldn't account for cases where you want to account for multiple occurrences and whatnot, but I'm not sure if that's required in your case.
Try this:
>>> d = [10, 5, 2, 3, 7]
>>> [sorted(d).index(i) for i in d]
[4, 2, 0, 1, 3]
This solution would work; however, there is probably a solution that is more space efficient. This solution does allow for repeat elements though.
l1 = [10, 5, 2, 3, 7] # Your list
l2 = sorted(l1) # Get the sorted version of our list.
# A dictionary containing each element and a list of the indices where they are found
element_indices = {}
for index, element in enumerate(l2):
if element not in element_indices:
element_indices[element] = [index] # Store the index for each element when it is sorted
else: # We have seen this element before
element_indices[element].append(index)
l2 = [element_indices[value].pop() for value in l1] # Change each element to its sorted equivalent index
print(l2) # [4, 2, 0, 1, 3]

List comprehension returns list of identical lists [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 5 years ago.
To my mind, the following code should simply reconstruct the input list, but instead I get a list of three copies of that list.
outlist = []
inputList = ["input1", "input2", "input3"]
def bar(input, outlist):
temp = input
outlist.append(temp)
return outlist
r1 = [bar(i, outlist) for i in inputList]
but my result
r1
Out[28]:
[['input1', 'input2', 'input3'],
['input1', 'input2', 'input3'],
['input1', 'input2', 'input3']]
Here is my I thought this would do:
Create an empty list
For each item in the input list, append that to outlist.
Return the result once it has gone through all three itemps in inputList.
So what am I missing/not understanding here? Why do I get a list of three identical lists, instead of just one of those lists by itself? Sorry if this has been asked before, but if it has, I was unable to find it (probably because I wasn't searching for the right terminology)
EDIT: Sorry if I wasn't clear. My goal is not to create a copy of a list, I just thought it would be a simple example to demonstrate the list of lists result. Please do not mark this as a duplicate of that question, because the list copying is not the subject of the question.
Edit2: My desired output:
['input1', 'input2', 'input3']
In other words, I want to make a list comprehension that iterates over a list, does something with the items in that list, and appends that item to a list which is the output. Here is another example, just to be clear that duplicating the original list is not my point:
outlist = []
inputList = [1, 2, 3]
def bar(input, outlist):
temp = input + 1
outlist.append(temp)
return outlist
r1 = [bar(i, outlist) for i in inputList]
r1
Out[31]:
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]
desired output:
[2,3,4]
Sorry if I'm being thick here..
EDIT:
In[71]: def bar(item):
...: return item + 1
...:
In[72]: [bar(i) for i in [1, 2, 3]]
Out[72]: [2, 3, 4]
In[73]: [i + 1 for i in [1, 2, 3]]
Out[73]: [2, 3, 4]

append values in a list without sorting python, keeping the appending order [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 7 years ago.
I am producing a list of list by this code, it is just a condition for a column of a dataframe named lvl or "Level", then append the index of this condition values, so the problem that i got is that the order of appending is important to me,
for i in range(1,int(24-lvl)):
j=list2[(list2.lvl==(lvl+i))]
jj=[]
jj.append(j.index)
print itertools.chain(jj)
well for example, the answer should be:
[0,100,110,500,501,550,555,89,120,114]
but i get the same list but sorted
[0,89,100,110,114,120,500,501,550,555]
itertools.chain works for me. You need to unpack the list before passing it to chain method.
>>> l = [[1,5],[10,2],[6,9,3]]
>>> list(itertools.chain(*l))
[1, 5, 10, 2, 6, 9, 3]
You can simply do it with list comprehension:
>>> l = [[1,5],[10,2],[6,9,3]]
>>> l_out = [item for sub_l in l for item in sub_l]
>>> l_out
[1, 5, 10, 2, 6, 9, 3]

Adding a duplicate item on to a list

I'm trying to add the last item of a list onto the list my code is:
def dup_last(data):
data.append([-1])
return data
and calling for the function is:
item = dup_last([1,2,3])
print(item)
but I want my output to be within only one set of brackets like:
[1, 2, 3, 3]
data.append([-1])
Here you are appending [-1], a list with an element of -1, change it to:
data.append(data[-1])
In addition to other answers, I would also suggest to use slicing notation [:] when dealing with lists to prevent getting list index out of range errors in case there is no item:
def dup_last(data):
data.append(data[-1])
return data
The above function will raise IndexError if data is empty list:
>>> print dup_last([])
----> 2 data.append(data[-1])
3 return data
4
IndexError: list index out of range
When you update your function as follows, you no longer get that kind of error:
def dup_last(data):
data.extend(data[-1:])
return data
>>> print dup_last([])
[]
>>> print dup_last([1])
[1, 1]
>>> print dup_last([1, 2])
[1, 2, 2]
There is a good explanation in this SO question about how slicing works in Python.
You need to do data.append(data[-1]); data.append([-1]) appends a value which is a list containing only -1, so your result will be [1, 2, 3, [-1]].
Note that this will modify the list in-place, so whichever list you pass in will also have the last element duplicated, not just the list you get out (though they could be the same list).
I wouldn't use a function for this; just do data.append(data[-1]) instead of data = dup_last(data), or even dup_last(data). Also, it's probably better to just add the duplicate manually if you're working with a list literal; data = [1, 2, 3, 3] vs data = dup_last([1, 2, 3]) or similar.

Categories