Vũ *_*Anh 2 python arrays string-formatting
我有以下字符串
myString = "cat(50),dog(60),pig(70)"
Run Code Online (Sandbox Code Playgroud)
我尝试将上面的字符串转换为2D数组.我想得到的结果是
myResult = [['cat', 50], ['dog', 60], ['pig', 70]]
Run Code Online (Sandbox Code Playgroud)
我已经知道使用遗留字符串方法解决的方法,但它非常复杂.所以我不想使用这种方法.
# Legacy approach
# 1. Split string by ","
# 2. Run loop and split string by "(" => got the <name of animal>
# 3. Got the number by exclude ")".
Run Code Online (Sandbox Code Playgroud)
任何建议都会表示赞赏.
您可以使用re.findall方法:
>>> import re
>>> re.findall(r'(\w+)\((\d+)\)', myString)
[('cat', '50'), ('dog', '60'), ('pig', '70')]
Run Code Online (Sandbox Code Playgroud)
如果你想要RomanPerekhrest注意到的列表列表,请将其转换为列表理解:
>>> [list(t) for t in re.findall(r'(\w+)\((\d+)\)', myString)]
[['cat', '50'], ['dog', '60'], ['pig', '70']]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
481 次 |
最近记录: |