![](/img/trans.png)
[英]How can I set and retain attributes on characters in a Python 2 string?
[英](Python) How can I add characters to a certain string in a set?
我對如何做到這一點有一些想法,但我真的不知道如何處理它。 我寫了這段代碼,它似乎不起作用,主要是因為我不知道集合是如何工作的。 它應該采用一個列表,如果任何字符串匹配,它將采用該字符串並將其設為復數,然后將其添加到集合中。
newSet = set()
for i in lst:
if lst.count(i) > 1:
newSet.add(i)
"s".join(newSet)
else:
newSet.add(i)
return newSet
每個str
都是不可變的。 我們可以分配name = 'cow'
,然后討論name + 's'
,但是那個復數字符串是一個單獨的字符串。 附加's'
對第一個字符串沒有影響。
最好用你想要的 go 來填充集合,而不是填充它然后改變主意。 這樣,當您將復數添加到集合中時,無需刪除單數。
cf 文檔。
from collections import Counter
animals = Counter(['cow', 'pig', 'cow', 'pig', 'sheep'])
print({name if count == 1 else f'{name}s'
for name, count in animals.items()})
編輯
f-string計算name + 's'
。
集合推導計算:
s = set()
for name, count in animals.items():
s.add(name) # or if you prefer, an expression that pluralizes
print(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.