[英]SQLAlchemy + Postgres (print created types, e.g. enum types)
[英]Finding documentation on python “native” types, e.g. set
我正在嘗試學習Python,盡管我設法迷失了對當前問題的答案,但我想知道將來如何更好地找到答案。
我的目標是將字符串列表作為輸入,並返回一個字符串,該字符串的字符是字符串中字符的並集,例如
unionStrings( ("ab", "bc"))
將返回“ abc”。
我是這樣實現的:
def unionStrings( strings ):
# Input: A list of strings
# Output: A string that is the (set) union of input strings
all = set()
for s in strings:
all = all.union(set(s))
return "".join(sorted(list(all)))
我覺得for循環是不必要的,並尋求更整潔,更多的pythonic(?)改進。
第一個問題 :我偶然發現使用類方法set.union()
而不是set1.union(set2)
。 我應該能夠在標准Python文檔中找到它嗎? 我無法在那找到它。
所以我嘗試像這樣使用set.union():
>>> set.union( [set(x) for x in ("ab","bc")] )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'union' requires a 'set' object but received a 'list'
我再次跌跌撞撞,終於發現我應該這樣稱呼它:
>>> set.union( *[set(x) for x in ("ab","bc")] )
set(['a', 'c', 'b'])
第二個問題 :我認為這意味着set.union
被(有效地)聲明為
set.union( *sets)
並不是
set.union( setsList )
那是對的嗎? (我仍在學習如何使用splat'*'。)
第三個問題 :在哪里可以找到有關set.union()
簽名的文檔? 我在set / freezeset文檔中沒有看到它,也無法獲取inspect
模塊給我任何東西。 我什至不確定set
是一個模塊,它似乎是一種類型。 是在模塊中定義的還是什么?
感謝您閱讀我的復雜問題。 更多的是“如何瀏覽Python文檔?” 而不是“如何在Python代碼中執行此操作?”。
回應jonrsharpe的評論:
哦! 我很習慣在C ++中定義單獨的靜態方法和實例方法。 現在,您已經解釋了,我真的可以看到發生了什么。
我唯一可能做的不同的是將其寫為
t = set.union( *[set(x) for x strings] )
return "".join(sorted(t))
因為在功能上它們沒有扮演不同的角色時,我覺得把strings[0]
與strings[1:]
中的strings[1:]
區別開來會困擾我。 如果我必須在其中之一上調用set()
,我寧願在所有它們上調用它,因為union()
無論如何都會這樣做。 但這只是樣式,對不對?
這里有幾個問題。 首先,您應該知道:
Class.method(instance, arg)
等效於:
instance.method(arg)
例如方法 。 您可以在類上調用方法並顯式提供實例,也可以僅在實例上調用它。
由於歷史原因,許多標准庫和內置類型都不遵循類名的UppercaseWords
約定,但它們是class 。 因此
set.union(aset, anotherset)
是相同的
aset.union(anotherset)
set
方法特別容易,因為它們經常被使用。 set.method(arg1, arg2, ...)
要求arg1
已經是set
,方法的實例,但是所有其他參數都將被轉換(從2.6開始)。
set
文檔中沒有直接涉及到這一點,因為對於所有情況都是如此。 Python非常一致。
在需要“啪啪”方面,請注意文檔說:
union(other, ...)
而不是
union(others)
也就是說,每個可迭代對象都是一個單獨的參數,因此您需要解壓縮可迭代對象列表。
因此,您的功能可能是:
def union_strings(strings):
if not strings:
return ""
return "".join(sorted(set(strings[0]).union(*strings[1:])))
或者,避免使用特殊的strings[0]
:
def union_strings(strings):
if not strings:
return ""
return "".join(sorted(set.union(*map(set, strings))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.