如何从整数列表中提取单个数字? [英] How to extract individual digits from a list of integers?

查看:54
本文介绍了如何从整数列表中提取单个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对python来说是新手,这给我带来了麻烦

Being new to python this has been giving me some trouble

给出一个整数列表,例如

Given a list of integers like

 [2, 0, 0, 0, 0, 12, 0, 8]

如何提取每个元素的单个数字以形成新列表

how might I extract the indiviual digits of each element to form a new list

 [2,1,2,8] 

我有遍历每个元素并使用模运算符的想法,但是我似乎找不到正确的逻辑

I've had the idea of iterating through each element and using the modulo operator but I cant seem to find the correct logic

非常感谢您的帮助

推荐答案

我认为,最简单的方法是将值转换为字符串并提取单独的字符,然后将其转换回整数.

The easiest way, I think, is to convert the values to string and extract separate characters and convert them back to integer.

例如:

lst = [2, 0, 0, 0, 0, 12, 0, 8]

digits = []
for value in lst:
    if value != 0:
        digits.extend(map(int, str(value)))

print(digits)

打印:

[2, 1, 2, 8]

这篇关于如何从整数列表中提取单个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆