4

So i have nested loops and array [[0, 1], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4]]:

for x in string_list:
        for y in string_list:
            print(x,y)

provides me the output

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6]
[0, 1] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6] [0, 1]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

But i have a lot of duplicates pairs and i did:

for x in range(0, len(string_list)):
      for y in range(x+1, len(string_list)): 
          print(x,y, string_list)

but it's working only for 2 digit pairs. So what i want is:

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6] 
[0, 1] [0, 1, 2, 3, 4]
**[0, 1, 2, 3, 4, 5, 6] [0, 1]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
**[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

does it possible to do without using itertools ? Thank you!

1
  • 2
    Is there a reason you don't want to use itertools? Commented May 7, 2020 at 17:33

4 Answers 4

7
for k, x in enumerate(string_list):
    for y in string_list[k:]:
        print(x,y)
Sign up to request clarification or add additional context in comments.

Comments

4

You can use itertools.combinations:

for x, y in it.combinations(string_list, 2):
    # process x, y

2 Comments

He doesn't want to use itertools.
@DanielWalker That's not a legitimate argument. The standard library exists to be used. And it can be used with minimal effort, the functionality is just one import away.
2

Obviously using itertools.combinations is ideal, but since you said you don't want to use itertools, you could use a set comprehension to build the set of unique combinations (you have to convert the lists to tuples to make them hashable), then convert them back to lists as needed:

[list(list(t) for t in f) for f in {
    frozenset((tuple(x), tuple(y))) for y in string_list for x in string_list
}]

3 Comments

This gives the exact same output as OP his output.
needed an extra layer of settification in there, fixed. :D
I might need a frozen set of ice cubes for the headache I now have. :)
-2

You can put a continue statement in the inner loop to skip duplicates:

 for x in string_list:
     for y in string_list:
         if x == y:
             continue
         print(x,y)

1 Comment

yes, but it will remove only: [0, 1] [0, 1], [0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4] [0, 1, 2, 3, 4], correct ? not what i want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.