简体   繁体   中英

Fill a list with a for loop python

Mine is not really a problem but the search for a solution, if any. And knowing this language necessarily exists. I have an integer 'n' and an integer 'p'. What I'm trying to do is divide n into digits, raise them to p and put them in a list. Later I will sum () the list. (Below is the code)

tot = sum([int(x)**p for x in str(n)])

The code works perfectly without any problems, the only thing I miss to add is that at each iteration, 'p' must be increase by 1. I have tried many things, and looked at a few other methods, but cannot find the correct syntax for adding this step. I really hope that some of you can help me find this solution. Many thanks in advance

Use enumerate to get an index which you can use to increase p by:

tot = sum([int(x) ** (p + i) for i, x in enumerate(str(n))])

If you want to start at p + 1 instead of p + 0 , use

tot = sum([int(x) ** (p + i) for i, x in enumerate(str(n), start=1)])

BTW, you don't even need to create the list. Remove the brackets to save some memory:

tot = sum(int(x) ** (p + i) for i, x in enumerate(str(n)))

You can use enumerate() inside your list comprehension to achieve this as:

>>> n = 12345
>>> p = 2

>>> sum([int(x)**(p+i) for i, x in enumerate(str(n))])
16739

enumerate() returns a tuple containing a count (from start which defaults to 0 ) and the values obtained from iterating over iterable.

You can pass start as 1 , if you want to start with p+1 as:

>>> sum([int(x)**(p+i) for i, x in enumerate(str(n), start=1)])
82481

A potential solution based on a for loop should be

tot = []

p = <whatever>

for x in str(n):
   temp = int(x) ** p 
   tot.append(temp)
   p = p + 1

sum(tot)

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