开发者

Rewrite this loop function with range

开发者 https://www.devze.com 2023-01-25 08:42 出处:网络
Is it possible to rewrite this loop: for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8],

Is it possible to rewrite this loop:

for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8], 
            [ca,9],[cb,10],[cc,12],开发者_开发百科[cd,13],[da,14],[db,15],[dc,16],[dd,17],...zd,220]]:

with two range functions or "list multiplication"? I have tried all sorts of approaches, but none worked so far.

Thank you.


If you have the objects in a list its actually quite simple:

object_list = [aa, ab, ... ]
for n, k in enumerate( object_list, start=1):
     ...

So you should look for a way to put them in a list instead.


You didn't give much information, so this might not be what you are looking for but:

l = [aa, ab, ... ]
for i in xrange(len(l)):
  k = l[i]
  n = i+1
  //the rest of your code

That being said, based on the names of your variables, it looks like you have a matrix of values. If that is the case, it would make more sense you use that kind of structure and just iterate over both indices rather than having lots of named variables.


Assuming you have these matplotlib in an iterable, objs:

([i, obj] for i, obj in enumerate(objs, 1))

This can be made much shorter and simpler if you used 2-tuples instead of lists of length two (you propably want this anyway!): enumerate(objs, 1).


If all those objects are in the modules global namespace you could do something like this:

from string import ascii_lowercase
n = 1
for a in ascii_lowercase:
    for b in ascii_lowercase[0:4]:
        k = globals()[a+b]
        n+=1

If they are in a function's namespace you could try locals() instead of globals()


try these.

[[j,i] for i,j in enumerate([c1+c2 for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]])]

[j,i] just for printing in the order you said. put function or whatever you want there.
or if you prefer loop to list-comp

for i,j in enumerate([c1+c2 for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]]):
    #loop body

im guessing aa thru zd are either in global namespace or (hopefully) a dict? just put either eval() or dict name around the c1+c2

for i,j in enumerate([dictname['c1+c2'] for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]]):
    #loopbody


A naive approach :

alphabet = ['a','b','c','d','e',] # Continue to have a complete alphabet

# Generator that returns every combination of a given alphabet with a given length
def xcombinations(items, n): 
    if n==0: yield []
    else:
        for i in xrange(len(items)):
            for cc in xcombinations(items[:i]+items[i+1:],n-1):
                yield [items[i]]+cc



gen = xcombinations(alphabet, 2)

for p,k in enumerate(gen):
    print ["".join(k), p]

Edit :

xcombinations can be replaced by itertools.permutations who does the same things.

0

精彩评论

暂无评论...
验证码 换一张
取 消