简体   繁体   中英

How to find all the two digit combinations of the elements in a list in python without using iterators and brute force

如果 List 由 1,2 和 3 作为元素组成所有可能的 2 位数字组合为 11 12 13 22 23 21 33 31 32

It depends on your definition of brute force...

L = [1,2,3]
L3 = [
    (l * 10) + l2
    for l in L
    for l2 in L
]

If L were defined as range(0, 10) then the maximum total combinations would be only 100, which on modern computers is no big deal. However, if you were considering extending this to more digits, then you might consider using a generator instead.

List comprehension will create a complete list in memory. Whereas the generator is used when you just want to iterate over the results and don't actually ever need all the elements in memory at the same time.

L = range(0, 10)
combinations = (
    (l * 100) + (l2 * 10) + l3
    for l in L
    for l2 in L
    for l3 in L
)

Notice the only difference here is the brackets.

Running this in ipython would give you something like this:

In [29]: combinations                                      
Out[29]: <generator object <genexpr> at 0x7f68103baad0>

The generator object can be iterated over, but the items are not calculated until they are being used. The generator can only be consumed once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM