Hey I'm trying to generate sublists of a list. For example I've a list like this:
l = [1,2,3,4,5,6,7,8,9,10,11,12]
I want to split them in sublists with the length of 4. But to first element is the same like the last element from the previous list AND like I said it must have the length of 4. Like this:
l1 = [1,2,3,4]
l2 = [4,5,6,7]
l3 = [7,8,9,10]
l4 = [10, 11, 12] <-- should be ignored
Does someone has an idea?! I'm thinking about an generator but I'm not quite sure.
A simple but flexible generator implementation:
def overlapping_sublists(l, n, overlap=1, start=0):
while start <= len(l) - n:
yield l[start:start+n]
start += n - overlap
Example usage:
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> list(overlapping_sublists(l, 4))
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]
>>> list(overlapping_sublists(l, 4, 2, 3))
[[4, 5, 6, 7], [6, 7, 8, 9], [8, 9, 10, 11]]
a = []
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for i in range(0, len(l)-3, 3):
a.append(l[i:i+4])
will give a = [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]
or you can use as a list comprehension:
[l[i:i+4] for i in range(0, len(l)-3, 3)]
print([l[i:i+4] for i in range(0, len(l), 3)])
Output:
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12]]
Only sublists of length 4:
print([m for m in [l[i:i+4] for i in range(0, len(l), 3)] if len(m) == 4])
Output:
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]
Using generators:
for n in (m for m in (l[i:i+4] for i in range(0, len(l), 3)) if len(m) == 4):
print(n)
Output:
[1, 2, 3, 4]
[4, 5, 6, 7]
[7, 8, 9, 10]
Related
I'm trying to take a list of numbers and increase them by a certain amount(1 in my example) up to a certain range(5 in my example) but for some reason it's not doing it the way I was expecting:
Given this list:
[1, 5, 7, 9, 3]
I expect:
[1, 5, 7, 9, 3]
[2, 5, 7, 9, 3]
[3, 5, 7, 9, 3]
[4, 5, 7, 9, 3]
[5, 5, 7, 9, 3]
[1, 6, 7, 9, 3]
[2, 7, 7, 9, 3]
[3, 8, 7, 9, 3]
[4, 9, 7, 9, 3]
[5, 10, 7, 9, 3]
... and so on
Here's my code:
# create list
list_of_nums = [1, 5, 7, 9, 3]
# variable of increase
increase_range = 5
range_per_increase = 1
for idx, i in enumerate(list_of_nums):
current_item = i
while current_item < i+increase_range:
copy_of_list = list_of_nums
current_item = current_item+range_per_increase
copy_of_list[idx] = current_item
print(copy_of_list)
break
Output:
[4, 7, 9, 11, 5]
[4, 8, 9, 11, 5]
[4, 8, 10, 11, 5]
[4, 8, 10, 12, 5]
[4, 8, 10, 12, 6]
What am I doing wrong or is there a easier way to get the output I want?
Update: I think my above example I get incrementals for each item then move on, but is it possible to get all combinations so the first item and the others item are incremented. I want all combinations for the lists within each numeric range while preserving the order.
There is an easier way to get this. The built in itertools.product method can do most of the work.
from itertools import product
list_of_nums = [1, 5, 7, 9, 3]
increase_range = 5
range_per_increase = 1
choices_list = []
for num in list_of_nums:
choices_list.append([])
currentAdder = num
while currentAdder < num + increase_range:
choices_list[-1].append(currentAdder)
currentAdder += range_per_increase
print(choices_list)
# Prints [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], ...] with all the options for each item.
print("\n\n\n")
for nums in product(*choices_list): # Unpack choices_list into product
print(list(nums)) # Since each output should be a list, convert from tuple to list
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
Example: I have a list:
[8, 3, 4, 1, 5, 9, 6, 7, 2]
And I need to make it look like this but without using numpy.array_split():
[[8, 3, 4], [1, 5, 9], [6, 7, 2]]
How can I do it? Not only for this one case, but when I have 4 elements, I want to have 2 and 2, (9 - 3,3,3 and 16 - 4,4,4,4) etc.
You can get the square root of the list's length then split it using a list comprehension. This will work for lists with the length of 4, 9, 16, ...:
lst = [8, 3, 4, 1, 5, 9, 6, 7, 2]
lst2 = [8, 3, 4, 1]
def split_equal(lst):
len_ = len(lst)
# returns emtpy list, if the list has no item.
if len_ == 0:
return []
n = int(len_ ** 0.5)
return [lst[i:i + n] for i in range(0, len_, n)]
output:
[[8, 3, 4], [1, 5, 9], [6, 7, 2]]
[[8, 3], [4, 1]]
You can use that:
def splitter(inlist):
n = len(inlist)
m = int(n ** 0.5)
if m*m != n:
raise Exception("")
return [[inlist[i+j] for j in range(m)] for i in range(m)]
print(splitter([8, 3, 4, 1]))
print(splitter([8, 3, 4, 1, 5, 9, 6, 7, 2]))
print(splitter([8, 3, 4, 1, 5, 9, 6, 7, 2, 8, 3, 4, 1, 5, 9, 6]))
Result:
[[8, 3], [3, 4]]
[[8, 3, 4], [3, 4, 1], [4, 1, 5]]
[[8, 3, 4, 1], [3, 4, 1, 5], [4, 1, 5, 9], [1, 5, 9, 6]]
Carefull, it will crash if the square of the len of input list is not integer.
def equal_array_split(arr, split_arr_len):
array_length = len(arr)
if array_length % split_arr_len == 0:
return [arr[i:i+split_arr_len] for i in range(0,array_length,split_arr_len)]
else:
return "Invalid split array length!!"
print(equal_array_split([1,2,3,4,5,6,7,8,9],3))
print(equal_array_split([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],4))
print(equal_array_split([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],8))
print(equal_array_split([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],2))
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
[[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
You can slice the list with a list comprehension. Assuming the input is a square number length:
import numpy as np
arr = [8, 3, 4, 1, 5, 9, 6, 7, 2]
n = int(np.sqrt(len(arr)))
result = [arr[i*n:(i+1)*n] for i in range(int(n))]
the split value being a square
list = [8, 3, 4, 1, 5, 9, 6, 7, 2]
result = []
N = split_value #split_value being the value required to split the list
for i in range(0,len(list),N):
result.append(list[i:i+N])
print(result)
Whitout numpy....
a = [8, 3, 4, 1, 5, 9, 6, 7, 2]
splitedSize = 3
a_splited = [a[x:x+splitedSize] for x in range(0, len(a), splitedSize)]
print(a_splited)
I am trying to learn recursion and am separating odd and even values in two lists and merging them to another list as below:
Code:
def separateNumbers(L):
evenList = []
oddList = []
main = []
if len(L)==0:
return L
if L[0] % 2 == 0:
evenList.append(L[0])
separateNumbers(L[1:])
if L[0] % 2 == 1:
oddList.append(L[0])
separateNumbers(L[1:])
main.append(evenList)
main.append(oddList)
return main
inputList = [1,2,3,4,5,6,7,8,9,10]
L = separateNumbers(inputList)
print(L)
Input:
L = [1,2,3,4,5,6]
Output:
[[1,3,5], [2,4,6]]
The even and odd arrays reset everytime the recursive function is called, how can I fix this?
Tried with inner function:
def separateNumbers(L):
evenList = []
oddList = []
main = []
def inner(L):
if len(L)==0:
return L
if L[0] % 2 == 0:
evenList.append(L[0])
inner(L[1:])
if L[0] % 2 == 1:
oddList.append(L[0])
inner(L[1:])
main.append(evenList)
main.append(oddList)
return main
a = inner(L)
return a
Output:
[[2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8,
10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
You don't need a nested function. try:
def separate_numbers(lst):
if not lst: # empty list
return [], []
odd, even = separate_numbers(lst[1:]) # recursion call
if lst[0] % 2: # if the first item is odd
return [lst[0], *odd], even
else: # if even
return odd, [lst[0], *even]
lst = [1,2,3,4,5,6,7,8,9,10]
print(separate_numbers(lst)) # ([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
The function calls itself using the tail part of the input list, receiving two lists: odd for odd numbers and even for even numbers. Then it returns those lists, after attaching the head element lst[0] to one of the lists.
Write List comprehensions to produce the following List pattern:
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
a= [2,3,4,5]
pattern = [ ]
l = [ ]
[pattern.append(i+j) for i in a for j in range(0,4)]
print(pattern)
With this code I could just print the output without putting them in the required pattern. Could someone help me out?
You could do:
a = [2, 3, 4, 5]
pattern = [[ai + j for ai in a] for j in range(0, 4)]
print(pattern)
Output
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
You could cast a range to a list for each element in a:
>>> a = [2, 3, 4, 5]
>>> sub_list_size = 4
>>> pattern = [list(range(x, x + sub_list_size)) for x in a]
>>> pattern
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
You can use itertools to perform rolling window operations.
from itertools import islice, tee
l = [i for i in range(2,10)]
#[2, 3, 4, 5, 6, 7, 8, 9]
def sliding_window(iterable, size):
iterables = tee(iter(iterable), size)
window = zip(*(islice(t, n, None) for n,t in enumerate(iterables)))
yield from window
[i for i in sliding_window(l,4)]
[(2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7), (5, 6, 7, 8), (6, 7, 8, 9)]
This one is causing me a headache, and I am having trouble to find a solution with a for-loop.
Basically, my data looks like this:
short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13] ]
I would need to know how many times each number from each row in the short_list appears in each row of the long_list, and the comparison is NOT needed when both list indices are the same, because they come from the same data set.
Example: I need to know the occurrence of each number in [1, 2, 3] in the long_list rows [2, 3, 4, 5, 6], [6, 7, 8, 9, 10] and [9, 10, 11, 12, 13].
And then continue with the next data row in short_list, etc.
Here's one way to do it. It's straight off the top of my head, so there is probably a much better way to do it.
from collections import defaultdict
short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13] ]
occurrences = defaultdict(int)
for i, sl in enumerate(short_list):
for j, ll in enumerate(long_list):
if i != j:
for n in sl:
occurrences[n] += ll.count(n)
>>> occurrences
defaultdict(<class 'int'>, {1: 0, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 0, 8: 0, 9: 1, 10: 1, 11: 0, 12: 0})
Note that enumerate() is used to provide indices while iterating. The indices are compared to ensure that sub-lists at the same relative position are not compared.
The result is a dictionary keyed by items from the short list with the values being the total count of that item in the long list sans the sublist with the same index.
This is a brute-force solution. I've amended the input data to make the results more interesting:
from collections import Counter
from toolz import concat
short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [2, 3, 11, 12, 13] ]
for idx, i in enumerate(short_list):
long_list_filtered = (x for x in concat(long_list[:idx] + long_list[idx+1:]) if x in set(i)))
print(idx, Counter(long_list_filtered))
# 0 Counter({2: 2, 3: 2})
# 1 Counter({4: 1, 5: 1, 6: 1})
# 2 Counter()
# 3 Counter({10: 1})
Possible Approach:
Loop over each list in short_list.
Flatten every list in long_list that is not the same index as the current list, and convert it to a set.
Create a collections.Counter() to store the counts for each element in short list that appears in the flattened list.
Demo:
from collections import Counter
from itertools import chain
short_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
long_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13]]
for i, short_lst in enumerate(short_list):
to_check = set(chain.from_iterable(long_list[:i] + long_list[i+1:]))
print(Counter(x for x in short_lst if x in to_check))
Output:
Counter({2: 1, 3: 1})
Counter({4: 1, 5: 1, 6: 1})
Counter({9: 1})
Counter({10: 1})
for L1 in short_list:
for L2 in long_list:
if not set(L1).issubset(set(L2)):
for x in L1:
print("{} has {} occurrences in {}".format(x, L2.count(x), L2))
short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13] ]
occ = []
for si in short_list:
occi = []
for i, e in enumerate(si):
count = 0
for li in long_list:
for j, e1 in enumerate(li):
if i == j:
continue
elif e == e1:
count += 1
occi.append(count)
occ.append(occi)
print occ
This should work,
Happy coding :)