如何在Python中将数字字符串范围转换为列表 [英] How to convert numeric string ranges to a list in Python

查看:435
本文介绍了如何在Python中将数字字符串范围转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将诸如"1,2,5-7,10"之类的字符串转换为诸如[1,2,5,6,7,10]之类的python列表.我环顾四周,发现了,但是我想知道是否有一种干净简单的方法可以在Python中做到这一点.

I would like to be able to convert a string such as "1,2,5-7,10" to a python list such as [1,2,5,6,7,10]. I looked around and found this, but I was wondering if there is a clean and simple way to do this in Python.

推荐答案

def f(x):
    result = []
    for part in x.split(','):
        if '-' in part:
            a, b = part.split('-')
            a, b = int(a), int(b)
            result.extend(range(a, b + 1))
        else:
            a = int(part)
            result.append(a)
    return result

>>> f('1,2,5-7,10')
[1, 2, 5, 6, 7, 10]

这篇关于如何在Python中将数字字符串范围转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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