【问题标题】:Adding different items to the list from the string从字符串向列表中添加不同的项目
【发布时间】:2018-02-12 19:01:54
【问题描述】:

比方说,有一个字符串可以是:

  • “3d6”
  • “t3d6”
  • “3h4d6”
  • “t3h4d6”
  • “6 t3d6”
  • “6 t3h4d6+6”和类似的可能变体。

有没有办法遍历字符串并根据它们是字母/数字/符号/其他内容将其中的项目添加到列表中?例如,"6 t3h10d6+6" 将导致 [6, " ", "t", 3, "h", 10, "d", 6, "+", 6] 作为列表。

我正在开发一个电报机器人,它使用 python 来用骰子计算结果来回答用户的输入,最难的部分是处理用户输入。现在正在通过笨拙的 if 语句处理输入。可能有更好的方法来处理用户输入,我很高兴听到您的建议!

与this question 不重复。问题是将字符串分解为字符列表,基本上是将字符串转换为字符串列表。我的问题是将字符串分解为可以是字符串和整数的不同项目的列表。

【问题讨论】:

标签: python list


【解决方案1】:

您也可以为此使用regex(通过指定查找所有数字和非数字字符):

>>> x
'6 t3h4df6d+!643'
>>> __import__("re").findall('\d+|\s+|\D+', x)
['6', ' ', 't', '3', 'h', '4', 'df', '6', 'd+!', '643']

如您所见,上述表达式并未将d 与+! 分开。 如果这是一个问题,您可以稍微修改上述常规 表达式为:

>>> x = '6 t3h4df6d+!643'
>>> re.findall('\d+|\s+|[a-zA-Z]+|\D+', x)
['6', ' ', 't', '3', 'h', '4', 'df', '6', 'd', '+!', '643']

将它们完全分开!

更新

如果您想将字符串拆分为单个字符(例如 "xy" 为 ['x','y']),您可以将上面的 regex 表达式更改为:

>>> x = '6 t3h4df6d+!643'
>>> __import__("re").findall('\d+|\s+|\w|\D+', x)
['6', ' ', 't', '3', 'h', '4', 'd', 'f', '6', 'd', '+!', '643']

【讨论】:

  • 非常非常pythonic
  • 你教会了我一个新东西。我什至不知道……天哪……__import__("re").findall(regex,variable) OMG!!!哇哇
  • 哇,谢谢!您似乎是唯一一个注意到 "10" 应该导致 [10] 而不是 [1, 0] 的人。
  • __import__("re").findall(regex,variable)我喜欢!
  • re.findall('\d+|\s+|\D+', "6 t3h10d6+1") 返回['6', ' ', 't', '3', 'h', '10', 'd', '6', '+', '1']。列表里面的项目都是字符串类型的,虽然问题中没有提到,但根本不是问题。
【解决方案2】:

如果您习惯使用列表推导式List comprehensions

  [ int(c) if c.isdigit() else c for c in "6 t3h4d6+6" ]

输出

[6, ' ', 't', 3, 'h', 4, 'd', 6, '+', 6]

【讨论】:

  • 请注意,这不会从"6 t3h10d6+6" 中提取10
【解决方案3】:

您可以使用groupby、isdigit 和列表推导来实现所需的结果:

from itertools import groupby
text = "6 t3h10d6+6"
substrings = groupby(text, lambda c: (c.isdigit(), c.isspace()))
print([int(''.join(l)) if d else ''.join(l) for (d, s), l in substrings])
# => [6, ' ', 't', 3, 'h', 10, 'd', 6, '+', 6]

注意'10' 被解析为10,而不是'10' 或[1, 0]。

【讨论】:

  • 我还注意到" t" 被解析为" t" 而不是[" ", "t"]。够近了!
  • @AntonyPetrushko:确实。 "ab"应该如何解析?
  • 好观察!很抱歉没有在问题中给出一个最好的例子。 "ab" 应解析为 ["a", "b"] 和 " b" 应解析为 [" ", "b"]。基本上它应该把一个字符串变成一个数字列表(不是数字)和单个字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-25
  • 2023-03-23
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多