How can i create multidimensional list in Python? - python

How can i create a multidimensional list while iterating through a 1d list based upon some condition.
I am iterating over a 1d list and whenever i find a '\n' i should append the so created list with a new list, for example,
a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]
so I want it to be as,
new_list = [[1,2,3,4],[6,7,8,9,0],[3,45,6,7,2]]
how should i do it? Please help
def storeData(k):
global dataList
dlist = []
for y in k:
if y != '\n':
dlist.append(y)
else:
break
return dlist
This is what i have tried.

example code:
lst = [[]]
for x in a:
if x != '\n':
lst[-1].append(x)
else:
lst.append([])
print(lst)
output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]

Using itertools.groupby would do the job (grouping by not being a linefeed):
import itertools
a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]
new_list = [list(x) for k,x in itertools.groupby(a,key=lambda x : x!='\n') if k]
print(new_list)
We compare the key truth value to filter out the occurrences of \n
result:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]

This is how I did it but there must be better solutions.
x = 0
output = [[]]
for item in a:
if item != "\n":
output[x].append(item)
else:
x += 1
output.append([])
print(output)

Here is the basic approach:
EDIT: Good heavens! Silly bug... here's a fix:
>>> sub = []
>>> final = []
>>> for e in a:
... if e == '\n':
... final.append(sub)
... sub = []
... else:
... sub.append(e)
... else:
... final.append(sub)
...
>>> final
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]
>>>
There are other ways, but this is the naive imperative way.

Related

List index out of range and giving the output ans still

`
list1 = [0,[1, 2, 3], [7, [5, 6]], [7], [8, 9]]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ans=[]
i = 0
n = len(list1)-1
while(n-2):
print(type(list1))
condition = (type(list1[i]) == int)
if condition == True:
ans.append(list1[i])
else:
for j in range(0, len(list1[i])):
condition1 = (type(list1[i][j]) == list)
if condition1 == True:
for k in range(0, len(list1[i][j])-1):
ans.append(list1[i][j][k])
else:
ans.append(list1[i][j])
i+=1
print(ans)
Can anyone help me`
I was trying to simplify the list and i used list for saving it but WHy Index of range. and Still my ans is getting save and giving the right output.
There are 5 items in list1 (see below):
0
[1, 2, 3]
[7, [5, 6]]
[7]
[8, 9]
Your code is incrementing beyond the index of this list
To flatten the list:
list1 = [0,[1, 2, 3], [7, [5, 6]], [7], [8, 9]]
def flatten_list(my_list):
is_not_Flat = True
my_list = [item for sublist in [item if type(item)==list else [item] for item in my_list] for item in sublist]
while is_not_Flat:
for item in my_list:
if type(item) == list:
my_list = flatten_list(my_list)
is_not_Flat = False
return my_list
print(flatten_list(list1))
Output:
[0, 1, 2, 3, 7, 5, 6, 7, 8, 9]

Why the 'list' is resulting empty after getting appended with a deleted list?

Here is my code, Could anyone please help me why the 'long_band' resulted in empty list?
Expected output: [[9,10],[0,1,2,3,4,5,6,7],[18],[12]]
Code begins here:
arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
len1 = len(arr)
long_band = list()
chain = list()
def band(i):
chain.append(i)
j = i+1
if j in arr:
band(j)
else:
#print(chain)
#print(long_band)
long_band.append([chain])
#print(long_band)
del chain[:]
def isHead(n):
x = n-1
if x in arr:
None
else:
band(n)
for i in range(len1):
isHead(arr[i])
print(long_band)
The immediate problem is this:
long_band.append([chain])
del chain[:]
You're appending the chain object to the list, and then immediately clear it. This also clears the object in the list, because there's only one object. Appending it to a list doesn't create a copy of it.
The bigger problem is that your algorithm is way overcomplicated. Here's a much simpler approach:
>>> arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
>>> arr.sort()
>>> res = [arr[0:1]]
>>> for i, j in zip(arr, arr[1:]):
... if i != j - 1:
... res.append([])
... res[-1].append(j)
...
>>> res
[[0, 1, 2, 3, 4, 5, 6, 7], [9, 10], [12], [18]]
arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
len1 = len(arr)
long_band = list()
chain = list()
def band(i):
chain.append(i)
j = i+1
if j in arr:
band(j)
else:
long_band.append(chain[:])
del chain[:]
def isHead(n):
x = n-1
if x in arr:
None
else:
band(n)
def FindMaxLen(long_band):
maxLength = max(len(x) for x in long_band)
print(maxLength)
for i in range(len1):
isHead(arr[i])
print(long_band)
FindMaxLen(long_band)

How can I make selecting highest number more compact with python?

I have this code where I have an array of sizes (i,j) and for each of the j variables, I want to select the highest out of the I variables.
For example, I have array [[2,5,1][12,4,6],[1,7,8],[2,4,5]] and I want to get the highest number out of each of the inner arrays so it should return: [5,12,8,5]
I have the following code which works fine, however, it's a bit messy and hard to read so my question is can I make it more compact?
Here is the code I have:
high_net_profit = list()
for i in range(len(self.accum_profit[0])):
high_value = 0
for j in range((len(self.accum_profit))):
if j == 0:
high_value = self.accum_profit[j][i]
else:
if self.accum_profit[j][i] > high_value: high_value = self.accum_profit[j][i]
high_net_profit.append(high_value)
Try:
lst = [[2, 5, 1], [12, 4, 6], [1, 7, 8], [2, 4, 5]]
out = [max(l) for l in lst]
print(out)
Prints:
[5, 12, 8, 5]
Or:
out = [*map(max, lst)]
print(out)
s = [[2,5,1][12,4,6],[1,7,8],[2,4,5]]
If you just need iterable object:
x = map(max, s)
If you need a list, then wrap into list:
x = list(map(max, s))
Here's a simple solution using numpy. Numpy is a very useful library when working with numbers:
import numpy as np
l_in = [[2, 5, 1], [12, 4, 6], [1, 7, 8], [2, 4, 5]]
# out = [max(l) for l in l_in] # can also be used
out = list(np.max(l_in, axis=1))
print(out)
Output:
[5, 12, 8, 5]

I want to remove duplicate from list (without for loop)

Here I have a list
a = [1, 2, 1, 4, 5, 7, 8, 4, 6]
Now I want a following output but without for loop.
Remove all the duplicate from the list.
[2, 5, 7, 8, 6]
output list contain only single occurrence number
Given: a = [1, 2, 1, 4, 5, 7, 8, 4, 6]
One liner:
b = [x for x in a if a.count(x) == 1]
You can use a Counter and a conditional list comprehension or filter in order to maintain the original order:
from collections import Counter
c = Counter(a)
clean_a = filter(lambda x: c[x] == 1, a) # avoids 'for' ;-)
# clean_a = list(filter(lambda x: c[x] == 1, a)) # Python3, if you need a list
# clean_a = [x for x in a if c[a] == 1] # would be my choice
This is a very simple and inefficient implementation.
We use a while loop to access every element of a. In the loop we check if the current element appears only once in the list. If yes, we add it to a new list.
a = [1, 2, 1, 4, 5, 7, 8, 4, 6]
index = 0
result = []
while index < len(a):
if a.count(a[index]) == 1:
result.append(a[index])
index += 1
print(result)
def cleaner(LIST, pos):
if len(LIST)>pos:
if LIST[pos] in LIST[pos+1:]:
LIST.pop(pos)
# OR
# LIST.remove(LIST[pos])
cleaner(LIST, pos)
else:
pos+=1
cleaner(LIST, pos)
return LIST
LIST = [1, 2, 1, 4, 5, 7, 8, 4, 6]
print(cleaner(LIST, 0))

python sum right and left components in list

I have a list:
key: [[1, 3, 4, 5, 3]]
I need to get list like
key: [[6, 5, 8, 7, 6]]
How can I do that with Python?
A simple approach:
>>> my_list = [1, 3, 4, 5, 3]
>>> new_list = []
>>> for i,x in enumerate(my_list):
... if i==0:
... new_list.append(my_list[-1] + my_list[i+1])
... elif i==len(my_list)-1:
... new_list.append(my_list[0] + my_list[i-1])
... else:
... new_list.append(my_list[i-1] + my_list[i+1])
...
>>> new_list
... [6, 5, 8, 7, 6]
you could use list comprehension:
[a[i-1]+(a+a[:1])[i+1] for i in range(len(a))]
this works because:
a[-1] returns the last element of the list
a+a[:1] appends the first element of the list to the end
A functional approach:
from operator import add
list(map(add, key[1:]+key[:1], key[-1:] + key[:-1]))
# [6, 5, 8, 7, 6]

Categories