對于給定的字串 s='ab12dc3e6' 我想在兩個不同的串列中添加 'ab' 和 '12' 。這意味著我試圖實作的輸出為 temp1=['ab','dc','e'] 和 temp2=['12,'3','6']。我無法使用以下代碼執行此操作。有人可以提供一種有效的方法嗎?
S = "ab12dc3e6"
temp=list(S)
x=''
temp1=[]
temp2=[]
for i in range(len(temp)):
while i<len(temp) and (temp[i] and temp[i 1]).isdigit():
x =temp[i]
i =1
temp1.append(x)
if not temp[i].isdigit():
break
uj5u.com熱心網友回復:
您也可以在沒有任何匯入的情況下解決此問題:
S = "ab12dc3e6"
def get_adjacent_by_func(content, func):
"""Returns a list of elements from content that fullfull func(...)"""
result = [[]]
for c in content:
if func(c):
# add to last inner list
result[-1].append(c)
elif result[-1]: # last inner list is filled
# add new inner list
result.append([])
# return only non empty inner lists
return [''.join(r) for r in result if r]
print(get_adjacent_by_func(S, str.isalpha))
print(get_adjacent_by_func(S, str.isdigit))
輸出:
['ab', 'dc', 'e']
['12', '3', '6']
uj5u.com熱心網友回復:
您可以使用正則運算式,將字母和數字分組,然后將它們附加到串列中
import re
S = "ab12dc3e6"
pattern = re.compile(r"([a-zA-Z]*)(\d*)")
temp1 = []
temp2 = []
for match in pattern.finditer(S):
# extract words
#dont append empty match
if match.group(1):
temp1.append(match.group(1))
print(match.group(1))
# extract numbers
#dont append empty match
if match.group(2):
temp2.append(match.group(2))
print(match.group(2))
print(temp1)
print(temp2)
uj5u.com熱心網友回復:
您的代碼對 isalpha 沒有任何作用-您還會遇到 IndexError on
while i<len(temp) and (temp[i] and temp[i 1]).isdigit():
為i == len(temp)-1.
您可以使用itertools.takewhile和str.isdigit和str.isalpha的正確字串方法來過濾您的字串:
S = "ab12dc3e6"
r = {"digit":[], "letter":[]}
from itertools import takewhile, cycle
# switch between the two test methods
c = cycle([str.isalpha, str.isdigit])
r = {}
i = 0
while S:
what = next(c) # get next method to use
k = ''.join(takewhile(what, S))
S = S[len(k):]
r.setdefault(what.__name__, []).append(k)
print(r)
輸出:
{'isalpha': ['ab', 'dc', 'e'],
'isdigit': ['12', '3', '6']}
這實際上創建了一個字典,其中每個單獨的串列都存盤在函式名稱下:
要獲取串列,請使用r["isalpha"]或r["isdigit"]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433682.html
