简体   繁体   English

将元素保持在列表中的位数相加达到一定值

[英]Keep elements in list whose digits add up to a certain value

From a list find out those values whose addition makes 9 从列表中找出加起来等于9的那些值

aList=[81,26,27,19,108]
output, 81(because: 8+1),27(because: 2+7) and 108 (because:1+0+8) 

I tried 2 approaches: 我尝试了2种方法:

1st approach: I could not find a way to get the value, just get the sum 第一种方法:我无法找到获取价值的方法,只是获取总和

s=[81,18]  
sum=0
for l in s:
    while l:
            l,dig=divmod(l,10)
            sum=sum+dig

print(sum)

2nd approach: Nasty one indeed. 第二种方法:确实令人讨厌。 Take individual values from list, convert to string to separate them and again convert to int. 从列表中获取单个值,转换为字符串以将其分开,然后再次转换为int。

s=[81]  #9

sum=0

for item in s: #81
    item=str(item) # 81 to string so I can get 8 and 1
    for i in item:
        while i:
            i =int(i)
            i,dig=divmod(i,10)
            sum=sum+dig

print(sum,item)

Problem: In both cases it only works when I have single value in the list. 问题:在两种情况下,它仅在列表中具有单个值时才起作用。 When I have more than 1 value aList=[81,18] it gives me sum of those 2. 当我的值大于1时aList = [81,18]会给我这两个值的总和。

I would appreciate some hints/ideas on this one. 我希望对此有一些提示/想法。 Thanks in advance. 提前致谢。

You could use the following list comprehension: 您可以使用以下列表理解:

l = [81,26,27,19,108]
[i for i in l if sum(int(d) for d in str(i)) == 9]
# [81, 27, 108]

Which is equivalent to the following for loop: 这等效于以下for循环:

res = []
for i in aList:
    temp = []
    for d in str(i):
        temp.append(int(d))
    if sum(temp) == 9:
        res.append(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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