第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 的另一個列表中制作一個總和數字列表?

如何在 Python 的另一個列表中制作一個總和數字列表?

UYOU 2021-09-11 13:28:55
例如,有沒有辦法輕松地將列表中的數字轉換為個位數population = ['10001','11111','11010','110001']into ['1','0','0','0','1'] add each digit in each set and put it in another list like thisevaluation = [2,5,3,3] (adding up all the 1's up on the first list)我對 Python 很陌生,所以我不確定我是否正確地做這件事
查看完整描述

3 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

如果您只處理零和一,那么@davedwards 是一個很好的解決方案。計算'1'每個字符串中的實例。

out = [x.count('1') for x in population]

如果您需要將解決方案更可擴展到 0 和 1 以外的值,您可以將每個數字轉換為 int 并對整數求和。

out = [sum(map(int, x)) for x in population]


查看完整回答
反對 回復 2021-09-11
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

使用collections.Counter():


>>> from collections import Counter

>>> population = ['10001','11111','11010','110001']

>>> [Counter(x).get('1', 0) for x in population]

[2, 5, 3, 3]

一種功能方法是還使用map()和operator.itemgetter():


>>> from collections import Counter

>>> from operator import itemgetter

>>> list(map(itemgetter('1'), map(Counter, population)))

[2, 5, 3, 3]


查看完整回答
反對 回復 2021-09-11
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊


一種可能的方法是遍歷population列表并使用str.count('character')計算'1'每個“數字”字符串中的 ':


evaluation = list(item.count('1') for item in population)

evaluation 將包含所需的計數:


>>> print(evaluation)

[2, 5, 3, 3]


查看完整回答
反對 回復 2021-09-11
  • 3 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號