Related
Lists are used to store multiple items in a single variable.
Lists are created using square brackets.
I want to reverse each item in the list of a list.
I tried reversed and [::1] method but it did not gave me desired output.
Here is my list
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
I tried print(list1[::-1]) and reversed(list1) and got this output
output: [[8, 9, 10], 7, 6, [4, 5, 6], 3, 2, 1]
How could I get this output?
output: [[10, 9, 8], 7, 6, [6, 5, 4], 3, 2, 1]
You can use a recursive function.
def revall(l):
return [revall(x) if isinstance(x, list) else x for x in l[::-1]]
print(revall([1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]))
Try this one:
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
list1.reverse()
for sub_list in list1:
if type(sub_list) is list:
sub_list.reverse()
print(list1)
I have a list like this
list = [[1, 2, 3, 4], [1, 9, 12], [9], [8], [7, 8, 9, 10, 12, 16], [7, 8, 9, 10], [4, 5, 6, 7], [6, 7, 8, 9, 10, 11]]
I need to find the k-th largest sublist by length of the list from the above-nested list, a small twist is there:
If K =2 the answer should be [4,5,6,7] as it comes later in the
processing
If K = 1 the answer should be [6, 7, 8, 9, 10, 11] as it comes later
in the processing
I initially sorted the nested sublist by length, which I think will be useful to find kth largest sublist, as it also preserves the order for list in which they were processed earlier
sorted_list = [[9], [8], [1, 9, 12], [1, 2, 3, 4], [7, 8, 9, 10], [4, 5, 6, 7], [7, 8, 9, 10, 12, 16], [6, 7, 8, 9, 10, 11]]
Not able to identify the correct way to find the kth largest element from here,
returning sorted_list[-K] will not work in most of the cases where the last two sublists are of same length.
Don't confuse lists elements with sorting, sorting is done on the basis of the length of sub-lists and order is preserved in sorted_list
You can do this with Python's itertools.groupby applied to your sorted list: then accessing index -k of the grouped list gives you all lists of the kth largest length, of which you wanted the last one:
import itertools
nums = [[1, 2, 3, 4], [1, 9, 12], [9], [8], [7, 8, 9, 10, 12, 16], [7, 8, 9, 10], [4, 5, 6, 7], [6, 7, 8, 9, 10, 11]]
sorted_list = sorted(nums, key=len)
grouped_list = [list(g) for k, g in itertools.groupby(sorted_list, len)]
def kth_largest(k: int):
return grouped_list[-k][-1]
print(kth_largest(k=2))
print(kth_largest(k=1))
gives:
[4, 5, 6, 7]
[6, 7, 8, 9, 10, 11]
You could use a dictionary to find the unique elements by length and then sort the values to find the corresponding kth element:
lst = [[1, 2, 3, 4], [1, 9, 12], [9], [8], [7, 8, 9, 10, 12, 16], [7, 8, 9, 10], [4, 5, 6, 7], [6, 7, 8, 9, 10, 11]]
# the dictionary will store the last appearing element of the corresponding key (the later one in the processing)
lookup = {len(e): e for e in lst}
# sort the values of the lookup dictionary, reverse by len
res = sorted(lookup.values(), key=len, reverse=True)
k = 2
print(res[k - 1])
k = 1
print(res[k - 1])
Output
[4, 5, 6, 7]
[6, 7, 8, 9, 10, 11]
I am trying to get indexes of a list store into a new list.
for example,
A = ['A', 'B', 'C',....,'Z']
and B list will select random no of indexes of A list like.
B = [[2,None,None], [1,None,None], [3,None,None],.....,[0, None,None]]
where list limit is, suppose, 10 and None will be replaced with the random no between 0 to 20 and finally the list of resultant look like,
result = [[2, 2, 3], [0, 4, 5], [8, 2, 4], [3, 8, 9]]
the first element in a sublist refers to the list A and the 2nd and third elements refer to the random selection of numbers between 0 to 10
Using random.sample.
import random
result = [random.sample(range(len(A)), 1) + random.sample(range(10), 2) for _ in range(10) ]
If you don't mind possible replication of values in the elements you can use a list comprehension, using random.randrange to generate the numbers:
result = [[random.randrange(26), random.randrange(10), random.randrange(10)] for _ in range(10)]
print(result)
Sample output:
[[18, 8, 1], [24, 1, 4], [24, 6, 5], [1, 4, 4], [7, 0, 9], [10, 7, 7], [0, 6, 9], [0, 9, 4], [6, 4, 4], [4, 2, 7]]
If you want to ensure no replication in each of elements of the list, you can use zip and random.sample to put together 3 lists of unique values and select values from those:
result = [[a, b, c] for a, b, c in zip(random.sample(range(26), 10), random.sample(range(10), 10), random.sample(range(10), 10))]
print(result)
Sample output:
[[2, 0, 1], [21, 4, 0], [11, 1, 4], [10, 7, 5], [15, 3, 3], [23, 6, 8], [25, 5, 2], [1, 9, 7], [24, 8, 9], [6, 2, 6]]
Think this basis for you
A = ['A', 'B', 'C','Z']
B = [[2,None,None], [1,None,None], [3,None,None],[0, None,None]]
for newb in B:
if newb[1] is None:
newb[1] = random.randrange(0,10)
if newb[2] is None:
newb[2] = random.randrange(0,10)
print(B)
it do like
[[2, 2, 2], [1, 6, 9], [3, 5, 7], [0, 6, 2]]
This question is an extension to this question.
I'm representing a two-dimensional array using list of lists, L, say:
[ [1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ]
For a given sub-list, say [9, 99], I want to replace a specific sub-list in the "2-D" list by this sublist using something intuitive like:
L[1][0:2] = sublist
# which updates `L` to:
[ [1, 2, 3, 4],
[1, 9, 99, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ] # not in this format, but written like this for clarity
This works for horizontal replacements, but not for vertical replacements since, as we can't slice to separate lists like this: L[0:2][0]. If I had to use this slicing system, I could transpose L (Transpose list of lists), then use this slicing method, then transpose it back. But that's not efficient, even for the sake of simplicity.
What would be an efficient way to replicate L[0:2][0] and get this output?
[ [1, 2, 3, 4],
[1, 9, 3, 4],
[1, 99, 3, 4],
[1, 2, 3, 4] ]
Note: Assume len(sublist) <= len(L), for vertical replacements (which is the focus of this question).
Looping approach:
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
print(a) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
replaceVert(a,['ä','ü'],2,2) # this is a one liner ;)
print(a) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 'ä', 12], [13, 14, 'ü', 16]]
Transpose/slice/transpose approach:
I overread the mentioning of "no transposing". This is using transpose, change, transpose method with slicing which is not wanted by the Q. It is a answer for the title of this question, so I decided to leave it in for future people search SO and stumble over this Q:
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
b = list(map(list,zip(*a))) # will make [ [1,5,9,13], ... ,[4,8,12,16]]
b[1][0:2]=['a','b'] # replaces what you want here (using a and b for clarity)
c = list(map(list,zip(*b))) # inverts b back to a's form
print(a)
print(b)
print(c)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # a
[[1, 5, 9, 13], ['a', 'b', 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]] # b replaced
[[1, 'a', 3, 4], [5, 'b', 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # c
Timing 4x4 list, 2 replaces:
setuptxt = """
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
"""
zipp = """b = list(map(list,zip(*a)))
b[1][0:2]=['a','b']
c = list(map(list,zip(*b)))
"""
import timeit
print(timeit.timeit("replaceVert(a,['ä','ü'],2,2)",setup = setuptxt))
print(timeit.timeit(stmt=zipp, setup=setuptxt))
Output:
looping: 12.450226907037592
zipping: 7.50479947070815
The method wit ZIPPing (transpose/slice/transpose) needs roughly 60% of the time for 4x4 lists.
Bigger list 1000x1000 and ~70 elements replaced:
setuptxt = """
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [kk for kk in range(1+pp,1000+pp)] for pp in range(1,1000)]
repl = [chr(mm) for mm in range(32,100)]
"""
import timeit
print(timeit.timeit("replaceVert(a,repl,20,5)",number=500, setup = setuptxt))
zipp = """b = list(map(list,zip(*a)))
b[20][5:5+len(repl)]=repl
c = list(map(list,zip(*b)))
"""
print(timeit.timeit(stmt=zipp, setup=setuptxt,number=500))
Output:
looping: 0.07702917579216137
zipping: 69.4807168493871
Looping wins. Thanks #Sphinx for his comment
I have a list sublists that I would like to search and check if two individual elements are within the same sublist. So for example, with 16 list elements in a randomized order,:
list=[[], [9, 10], [1, 2, 8, 13], [0, 3, 6, 14], [5, 7, 11], [],]
#Max number of classes
MaxN=5
for k in range(0,MaxN):
for i in list[k]:
##if (check whether i exists in same sublist as i+1):
continue
else
foo()
So that connections between [9, 10], [1, 2], [1, 8], [1, 13], [2, 8], [2, 13], [8, 13], [0, 3], [0, 6], [0, 14], [3, 6], [3, 14], [6, 14], [5, 7], [5, 11], [7, 11] will all be skipped, and the operation foo will be performed on the rest of the list.
I tried:
for k in range(0,MaxN):
for i in list[k]:
if list[i]==list[i+1]:
print 'skipped'
else:
print 'included'
But I get a list index out of range error, which I don't seem to understand.
Try This:
>>> output=[]
>>> list=[[], [9, 10], [1, 2, 8, 13], [0, 3, 6, 14], [5, 7, 11], []]
>>> for l in list:
for i in range(len(l)):
for j in range(i+1,len(l)):
output.append([l[i],l[j]])
>>> output
[[9, 10], [1, 2], [1, 8], [1, 13], [2, 8], [2, 13], [8, 13], [0, 3], [0, 6], [0, 14], [3, 6], [3, 14], [6, 14], [5, 7], [5, 11], [7, 11]]
After getting output list, you can simply try with the help of "in" keyword:
>>> for k in range(5): #or range(maxN)
if (list[k] in output):
print("skipped")
else:
print("included")
included
skipped
included
included
included
I'm not sure I understand what you're trying to do. I read your problem as, you're trying to look at a list, and see if any of its elements are in any of the subsquent lists. If so you want to do something like the following (NOTE I changed your variable to my_list, calling something list in python is dangerous because you can no longer use it to make actual lists)
my_lists=[[], [9, 10], [1, 2, 8, 13], [0, 3, 6, 14], [5, 7, 11], [],]
n_sub_lists = len(my_list)
for k in range(0,n_sub_lists):
for i in my_lists[k]:
for j in range(k, len(n_sub_lists)):
if i in my_lists[j]:
continue
else:
foo()
I also removed your MaxN variable because I wasn't sure of it's purpose. If I was mistaken there please comment and I'll update appropriately