簡體   English   中英

如何從 Python 中的字符串中提取特定字符?

[英]How to extract specific characters from a string in Python?

說我有一個這樣的字符串:

coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87

我想將值存儲在 8 個變量中:

xCoord1 = 22
yCoord1 = 45
xCoord2 = 144
yCoord2 = 56
xCoord3 = 26
yCoord3 = 13
xCoord4 = 144
yCoord4 = 87

注意:坐標只能是 2 或 3 位數字。

最好創建一個字典來保存 output。

您可以使用re.findall提取鍵/值和字典理解來生成 output。

鍵的自動遞增可以通過collections.defaultdictitertools.count的組合來完成

s = 'coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87'

import re
from itertools import count
from collections import defaultdict

counter = defaultdict(lambda:count())

coords = {f'{k}Coord{next(counter[k])+1}': int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

output:

{'xCoord1': 22,
 'yCoord1': 45,
 'xCoord2': 144,
 'yCoord2': 56,
 'xCoord3': 26,
 'yCoord3': 13,
 'xCoord4': 144,
 'yCoord4': 87}

然后通過按名稱選擇協調來訪問您的值:

>>> coords['xCoord1']
22
元組作為鍵:

我什至更喜歡使用元組作為鍵:

counter = defaultdict(lambda:count())
coords = {(k, next(counter[k])+1): int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

coords['x', 1]
# 22

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM