我正在嘗試將這個字串 '4-6,10-12,16' 轉換成一個看起來像這樣的串列 [4,"-",6,10,"-",12,16]。串列中會有整數和特殊字符“-”的組合。
我試圖在 python 中使用正則運算式代碼,但我只能提取數字,但是,我也需要串列中的破折號。如何在串列中包含帶有數字的破折號?
這是我的代碼:
interval='4-6,10-12,16'
import re
l=[int(s) for s in re.findall(r'\b\d \b', interval)]
uj5u.com熱心網友回復:
試試這個:
interval='4-6,10-12,16'
import re
l=[int(s) if s.isnumeric() else s for s in re.findall(r'\d |-', interval)]
l
輸出:
[4, '-', 6, 10, '-', 12, 16]
uj5u.com熱心網友回復:
您可以使用
import re
interval='4-6,10-12,16'
l=[int(s) if all(c.isdigit() for c in s) else '-' for s in re.findall(r'\d |-', interval)]
print(l) # => [4, '-', 6, 10, '-', 12, 16]
請參閱Python 演示。
詳情:
re.findall(r'\d |-', interval)提取數字序列或-字符int(s) if all(c.isdigit() for c in s) else '-'int如果整個匹配由數字組成,則將數字序列轉換為,或者僅-作為字串回傳。
uj5u.com熱心網友回復:
有用的功能:
str.isdigit(或str.isnumeric或str.isdecimal);itertools.groupby將具有相同特征的相鄰字符分組。
from itertools import groupby
def tokenize_digits_and_dashes(s):
for k, g in groupby(s, key=lambda c: (c.isdigit(), c == '-')):
if k == (True, False):
yield int(''.join(g))
elif k == (False, True):
yield '-'
print(list(tokenize_digits_and_dashes('4-6,10-12,16')))
# [4, '-', 6, 10, '-', 12, 16]
替代方法
您的字串已經包含逗號形式的分隔符,。這些很有用!不要忽視他們。您可以使用分隔符拆分串列str.split。
def tokenize_intervals(s):
for interval in s.split(','):
i = interval.split('-')
if len(i) == 2:
yield tuple(int(''.join(w)) for w in i)
elif len(i) == 1:
x = int(''.join(i[0]))
yield (x, x)
print(list(tokenize_intervals('4-6,10-12,16')))
# [(4, 6), (10, 12), (16, 16)]
uj5u.com熱心網友回復:
# By Using Regex #
# -------------- #
import re
interval = '4-6,10-12,16'
s_list = re.findall(r'[\d ] |-', interval)
x = [int(_) if _.isnumeric() else _ for _ in s_list]
print(x)
# By Using the split method #
# ------------------------- #
final_list = []
for _ in interval.split(','):
sub_list = _.split('-')
for i in sub_list:
if i.isnumeric():
final_list.append(int(i))
if sub_list[-1] != I:
final_list.append('-')
print(final_list)
# By Checking Character By Character #
# ---------------------------------- #
z = ""
s = []
count = 0
for _ in interval:
count = 1
if _.isnumeric():
z = _
if count == len(interval):
s.append(int(z))
elif _ == '-':
s.append(int(z))
z = ""
s.append('-')
else:
s.append(int(z))
z = ""
print(s)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475201.html
標籤:Python python-3.x 正则表达式 算法
