Lefty Lefty - 6 months ago 13
Python Question

Python - How to add local variables based on number of n provided

I have a function that takes in a list and n number. I'd like to create something like this:

def create_list_sets(lst, n):
if n == 1:
for i in range(len(lst)-1):
res = [lst[i], lst[i+1]]
return res
if n == 2:
for i in range(len(lst)-1):
res2 = [lst[i], lst[i+1], lst[i+2]]
return res2


Only I dont want to write
n == 2, n == 3... n == n
. More specifically, if my
def create_list_sets(lst, n)
takes
n == 4
I want res to eqaul
[lst[i], lst[i+1], lst[i+2], lst[i+3], lst[i+4]]
, without hardcoding this in.

Here is the full code I'm working on:

###########
# Library #
###########

def number_to_be_tested():
number_tested = 34278698769876978697687693454
return number_tested


def number_split(object):
lst = []
string_the_number = str(object)
for digit in string_the_number:
lst.append(int(digit))
return lst


def create_list_sets(lst, n):
if n == 1:
for i in range(len(lst)-1):
res = [lst[i], lst[i+1]]
return res
if n == 2:
for i in range(len(lst)-1):
res2 = [lst[i], lst[i+1], lst[i+2]]
return res2

##################################
# Script / Application / Program #
##################################

def main():
test_number = number_to_be_tested()
test_lst = number_split(test_number)
list_sets = test_lst(test_lst, 2)
print list_sets

if __name__ == '__main__':
main()


How can I accomplish my goal? Also as you can see, it will create a Traceback at the end of the program, I'm not concerned about this atm -- that said, if you know how to also help me in this, I would very much appreciate it.

Answer

Since you know n and have the full lst and the value of n you can use the append

def create_list_sets(lst, n):
    res = []
    if n <= len(lst):
        for i in range(n):
           res.append([lst[i])
    return res

Note that this assumes that you want an empty list to return as an error when n > len(lst). If you just want to reset n to len(lst) if n is too large then use

def create_list_sets(lst, n):
    res = []
    if n >= len(lst):
        n = len(lst) -1
    for i in range(n):
        res.append([lst[i], lst[i+1]])
    return res

my apologies for not being specific in my question. You have it right on the head. I do want one more functionality. if n ==4 i want what you provided. but I want it for each index. so: if n == 2 -> res = [lst[0], lst[1]], [lst[1], lst[2]], [lst[2], lst[3]], [lst[3], lst[4]]…] – Lefty 2 hours ago

def create_list_sets(lst, n):
    res = []
    if n > len(lst):
        n = len(lst)
    for k in range(len(lst) - n + 1)
        tmp = []
        for i in range(n):
            tmp.append(lst[i+k])
        res.append(tmp)
    return res

Note that the inner loop can be replaced by a slice

def create_list_sets(lst, n):
    j = len(lst)
    res = []
    if n > j:
        n = j
    for k in range(j - n + 1)
        res.append(lst[k:k+n])
    return res