I want to iterate the second loop through the second position
My error is
Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: ) can only concatenate list (not "int") to list
s = "dog cat cat dog"
b = list(s.split(" "))
for x in b:
for y in str(b 1):
print(x,'/', y)
CodePudding user response:
A way to fix your code is:
s = "dog cat cat dog"
b = list(s.split(" "))
for x in b:
for y in b[1:]:
print(x,'/', y)
Even though I don't think it does what it is supposed to do, because the output is:
dog / cat
dog / cat
dog / dog
cat / cat
cat / cat
cat / dog
cat / cat
cat / cat
cat / dog
dog / cat
dog / cat
dog / dog
Maybe you wanted something like
s = "dog cat cat dog"
b = list(s.split(" "))
for x,y in zip(b,b[1:]):
print(x,'/', y)
Output:
dog / cat
cat / cat
cat / dog
CodePudding user response:
Answer based on your comment
If you simply want to loop through a list twice where the second loop is the remainder of the list, you can use
s = "dog cat cat dog"
b = s.split(" ")
for i in range(len(b)):
for j in range(i 1, len(b)):
# i is the first index, j is the indices of the remaining entries
# So x = b[i], y = b[j]
Old answer
I am not sure I fully understand what you're searching for, perhaps something like this?
s = "dog cat cat dog"
b = s.split(" ")
for i in range(len(b)):
for j in range(i 1, len(b)):
print(b[i],'/', b[j])
which returns
dog / cat
dog / cat
dog / dog
cat / cat
cat / dog
cat / dog
Also, you don't need to cast a call to split() to a list, as it already returns a list.
