-1

My code is:

s = "bananban"  
x = 0
a = 0
s = list(s)
K = [] 
S = [] 
#F = [] 
A1=[]



def Buchstaben(s):
    for i in s:
        
        if not K.__contains__(i):
            K.append(i)


def vergleich(s):
    global x
    global a
    global S
    F =[]
    
    for j in s:
        x += 1
        
        if not F.__contains__(j):
            a += 1
        
        S.append(j)

        if a == len(K):
            print(F)
            S.append(F)
            
            print(S)
            a = 0

            print(S)
        
        if len(s) == x:
            S.append(F)
    

Buchstaben(s)
vergleich(s)
print(S)

As a output I get:

['b', 'a', 'n', [], 'a', 'n', 'b', [], 'a', 'n', []]

But I need:

[['b', 'a', 'n'],['a', 'n', 'b'],['a', 'n']]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Don't you want to append to `F` sometimes, not always `S`? You should try some basic debugging. – jonrsharpe Jan 21 '22 at 14:26
  • 1
    What actually is the goal of the code? How do you know that `[['b', 'a', 'n'],['a', 'n', 'b'],['a', 'n']]` is correct? What is the rule that tells you where to make the splits? – Karl Knechtel Jan 21 '22 at 14:27
  • The title makes it sound like you want to fix the output after the fact, but I really think you should try to make the code give the right answer the first time. – Karl Knechtel Jan 21 '22 at 14:29
  • Does https://stackoverflow.com/questions/312443/how-do-you-split-a-list-or-iterable-into-evenly-sized-chunks help? – Karl Knechtel Jan 21 '22 at 14:30
  • Your requirement looks very similar to the one answered [here](https://stackoverflow.com/a/70792047/5237560) – Alain T. Jan 21 '22 at 14:40

1 Answers1

0

If you're trying to split the "bananban" string into every 3 characters, you can try the following:

s = list("bananban")
def split_str(str, char):
    k, m = divmod(len(str), char)
    return (str[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(char))
print (list(split_str(s, 3)))

Output:

[['b', 'a', 'n'], ['a', 'n', 'b'], ['a', 'n']]
peru_45
  • 330
  • 3
  • 16