简体   繁体   中英

How to call a tuple of the enumerate function?

I am trying to run a for loop in order to edit the index of a data-frame. In general though, I can't seem to understand how the enumerate function really works.

Say for instance I have a simple list such that:

eg = ["A","B","C","D","E"]

for i,j in enumerate(eg):
    print(i,j)

This returns a simple and easily understandable output of:

0  A
1  B
2  C
3  D
4  E

Hence, i is the count in the list and j is the actual value. But say I wanted to run something a little more complicated like the below:

indx = []

for i,j in enumerate(eg):
    if i < 4:
        indx.append(str(j[i]) + str(j[i+1]))
    else:
        next

print(indx)

Essentially I would like to concatenate consecutive entries in a meaningful manner, such that the desired output for the code above (if I actually knew what I was doing) would be something like:

indx = ['AB', 'BC', 'CD', 'DE']

Ideally though, the for-loop would be able to concatenate these letters with the distance increasing one at a time, that is:

indx = ['AB', 'BC', 'CD', 'DE', 'AC', 'BD', 'CE', 'AD', 'BE', 'AE']

Not sure if what I am asking is fairly simple and I am missing something obvious, or if it would just be easier for me to go through the effort of manually specifying the list like I have above.

Any help however is greatly appreciated:)

Here j used in for loop is element of the list so you should not index that like j[i] . Use indx[i] and indx[i+1] while you are concatenating inside for loop.

I guess what you need is the combinations of the items in eg . You can use the combinations method of the itertools package as follow:

from itertools import combinations
eg = ["A","B","C","D","E"]
[''.join(m) for m in combinations(eg,2)]

output:

['AB', 'AC', 'AD', 'AE', 'BC', 'BD', 'BE', 'CD', 'CE', 'DE']

if the order is important, you need to do it manually. You can do it in a nested loop like this:

stack = []
step_max = len(eg)
for j in range(1,step_max):
    for i in range(len(eg)-j):
        stack.append(str(eg[i])+str(eg[i+j]))

print(stack)

output:

['AB', 'BC', 'CD', 'DE', 'AC', 'BD', 'CE', 'AD', 'BE', 'AE']

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