This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
Hi I am a beginner to python and I have an exam tomorrow. I do not know how to do this question. I know that I have to use a nested for loop but, I cannot make it work syntactically. Here is the question, I apologize for any formatting errors.
(list of int, int) -> list of (list of int)
Return a list of lists of elements from 1st,
where each sublist is the next num elements from 1st.
If the length of 1st is not a multiple of num, the final sublist will have fewer than num elements.
ยป> make_rows([2. 4, 6, 8, 10, 12],3) #Function call
[[2, 4, 6], [8, 10, 12]] # expected output
do something like this:
def separate(lst, index):
new_list = [lst[i:i+index] for i in range(0, len(lst), index)]
return new_list
it will return like so:
>>> print separate([1,2,3,4,5,6],3)
[[1, 2, 3], [4, 5, 6]]
Here is an extremely verbose solution that's not very Pythonic, but shows in detail the steps one would take without List comprehensions or functional style.
The original poster mentioned for-loops, so I thought he may want an iterative approach.
def make_rows(list_of_int, num_per_row):
new_list = []
count = 0
new_inner_list = []
for n in list_of_int:
count += 1
new_inner_list.append(n)
if (count == num_per_row):
new_list.append(new_inner_list)
new_inner_list = []
count = 0
return new_list
Related
This question already has answers here:
What is the best way to iterate over multiple lists at once? [duplicate]
(2 answers)
Closed 4 years ago.
The inputs will be lists (which is the number of list is indefinite), the function is supposed to iterate through all the index and add each value of the list for same index for all the inputted list mathematically together. The output will be the a list which consist of all the added values
For example:
lista = [1,2,3] listb = [2,3,5] listc = [-3,2,1]
outputlist = [0,7,9]
My function below is only able to add 2 list together, I want no restrictions as to how many list. How do I do that?
Thank you very much in advance
def listadd(a,b):
counter = 0
list = []
while counter < len(a):
list.append(a[counter]+b[counter])
counter += 1
return list
You can use map with zip:
def listadd_new(*lsts):
return list(map(sum, zip(*lsts)))
assert listadd([1, 2, 3], [4, 5, 6]) == listadd_new([1, 2, 3], [4, 5, 6])
This question already has answers here:
How to find common elements in list of lists?
(7 answers)
Closed 4 years ago.
I have a list of lists:
[[10, 9, 8], [8, 7], [1, 2, 3]]
The sublists are not necessarily of the same size.
I need to find a number that occurs in two seperate lists, and return the list index and the numbers index in those lists.
in this case it would be 8, list 0, list 1, list 0 idx 2, list 1 idx 0.
Right now I am doing it with a bunch of for loops, but this is ridiculously slow... are there are faster more pythonic way of achieving this?
You can enumerate the lists and items in the list and store the index-tuples for each element in a dict, then filter those entries that have more than two occurrences.
lst = [[10, 9, 8], [8, 7], [1, 2, 3]]
in_list = collections.defaultdict(list)
for i, x in enumerate(lst):
for k, y in enumerate(x):
in_list[y].append((i, k))
res = {k: v for k, v in in_list.items() if len(v) > 1}
# {8: [(0, 2), (1, 0)]}
(This assumes that no element appears more than once in the same sublist.)
While this also uses "a bunch of for loop" (depending on your definition of "a bunch"), it will visit every element in the nested list only exactly once, giving it O(n) (n = comb. size of lists).
from itertools import combinations
search = list(combinations(range(len(solutions)), 2))
for i in search:
res = list(set(solutions[i[0]]) & set(solutions[i[1]]))
if len(res) != 0:
save = [i, res[0]]
idxList1 = solutions[save[0][0]].index(save[1])
idxList2 = solutions[save[0][1]].index(save[1])
This does what it is supposed to, but it seems like a poor solution.
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
So I have a problem where I need to remove the integers that occur more than n times from the list. This is giving me an error that remove(x) doesn't exist in the list. Help!
def answer1(data, n):
for i in range(len(data)):
item = 0
if data.count(i) > n:
item = i
for k in range(len(data)):
data.remove(item)
print(data)
data = [1, 2, 3, 1, 1, 2, 2, 3, 4 ,5]
answer1(data, 2)
Your code doesn't work properly because you're removing items from your list while iterating on it. This shortens the list, but the loop iterating on it isn't aware of that (because of its internal index counter)
I would use collections.Counter to count the occurrences (good performance, as opposed to count which scans the list at each iteration) then filter the list using a list comprehension (as a bonus, the original input isn't modified)
import collections
def answer1(data, n):
c = collections.Counter(data)
return [x for x in data if c[x]<n]
data = [1, 2, 3, 1, 1, 2, 2, 3, 4 ,5]
a = answer1(data, 2)
print(a)
result:
[4, 5]
(and the initial order is preserved)
This question already has answers here:
Sum a list of lists to get a sum list Python
(2 answers)
Closed 5 years ago.
First off, I am really new to python, and programming in general, and I'm struggling to grasp the concept of nested for loops and nested lists.
In my code below I am trying to take each list inside the list list1 and sum them using a for loop. I am aware that the range function would help somehow.
Code:
def sum_list(list1):
list_of_sums = []
total = 0
for l in list1:
for value in l:
total = total + value
list_of_sums.append(total)
return list_of_sums
Input test:
list1 = [[4, 7, 9], [4, 5, 2], [4, 5, 6]]
print(sum_list(list1))
Output:
[4, 11, 20]
Desired output:
[20, 11, 15]
You have some logical issues in your code. Think carefully when you should reset total and when to append result to the list_of_sums.
def sum_list(list):
list_of_sums = []
for sublist in list:
total = 0
for value in sublist:
total += value
list_of_sums.append(total)
return list_of_sums
you can achieve this by using list comprehension, it's one of the best thing provided by python. it really shirnks you code and yet easy to understand.
following post my help. You can google more on list comprehension, if you like
http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/
def sum_list(list1):
return [sum(inner_list) for inner_list in list1]
print sum_list([[4, 7, 9], [4, 5, 2], [4, 5, 6]])
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Flatten (an irregular) list of lists in Python
for instance, from:
[[1,2,3],'a',[[4],[5,6],7]]
we want to flatten/penetrate the structure and get all the elements at bottom listed in a line:
[1,2,3,'a',4,5,6,7]
# a recursive function to flatten arbitrary nested lists into one simple 1D list
def flatten(inlist,outlist):
for e in inlist:
if isinstance(e,list) :
flatten(e,outlist)
else:
outlist.append(e)
it's a practice of recursive function, :). the "outlist" here serves as a reference for return-list.
there must be better structures...
;)
for example:
For your benefit, here is an implementation that modifies the list in-place:
def flatten_in_place(seq):
if isinstance(seq, list):
for index, item in reversed(list(enumerate(seq))):
if isinstance(item, list):
seq[index: index + 1] = fil(item)
return seq
else:
return [seq]
Usage:
>>> l = [[1, 2], [3, 4], 5, 6, [7, [8, 9]]]
>>> flatten_in_place(l)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Interestingly enough, the timeit results (t = 1,000,000) show this to be slightly faster than your implementation:
flatten_in_place time: 4.88
flatten time: 5.16
I'm not sure why that is exactly. Any ideas?