I'm making a function that takes a variable number of lists as input (i.e., an arbitrary argument list). I need to compare each element from each list to each element of all other lists, but I couldn't find any way to approach this.
相关问题
- Is there a limit to how many levels you can nest i
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
I think @LevLeitsky's answer is the best way to do a loop over the items from your variable number of lists. However, if purpose the loop is just to find common elements between pairs of items from the lists, I'd do it a bit differently.
Here's an approach that finds the common elements between each pair of lists:
I'm not sure what you need to do with the common elements, so I'll leave it there.
The itertools module provides a lot of useful tools just for such tasks. You can adapt the following example to your task by integrating it into your specific comparison logic.
Note that the following assumes a commutative function. That is, about half of the tuples are omitted for reasons of symmetry.
Example:
Output:
Depending on your goal, you can make use of some of the
itertools
utilities. For example, you can useitertools.product
on*args
:But currently it's not very clear from your question what you want to achieve. If I didn't understand you correctly, you can try to state the question in a more specific way.
if you want the arguments as dictionary
if you want all the arguments as list:
you can use both
call it like that: