![](/img/trans.png)
[英]python “too many to unpack” when unpacking a tuple returned by a function
[英]Python: Unpack individual strings from tuple using Unpacking asterisk argument
在以下代碼中,我試圖通過遍歷作為長度和字符串類型不同的參數輸入的所有單詞來創建一個新單詞。 我在這里閱讀*運算符使它成為非關鍵字可選參數。
def gen_new_word(word1,*nwords):
new_word=''
t0=[i for i in nwords]
t=max(word1,max(t0))
print (t),str(len(t)) #check largest string
for i in xrange(len(t)):
try:
print 'doing iter i# %s and try' %(i)
new_word=new_word+(word1[i]+nwords[i])
print new_word
except IndexError,e:
print 'entered except'
c=i
for x in xrange(c,len(t)):
print 'doing iter x# %s in except' %(x)
new_word=new_word+t[x]
break
return new_word
輸出:
gen_new_word('janice','tanice','practice')
tanice 6
doing iter i# 0 and try
jtanice
doing iter i# 1 and try
jtaniceapractice
doing iter i# 2 and try
entered except
doing iter x# 2 in except
doing iter x# 3 in except
doing iter x# 4 in except
doing iter x# 5 in except
Out[84]: 'jtaniceapracticenice'
Q1:為什么不給“練習”作為最大字符串,為什么給max(word1,max(t0))
提供tanice?
問題2:t = max(word1,max(t0))有效,但max(word1,nwords)無效。 為什么&對此有解決方法?
問題3:在new_word=new_word+(word1[i]+nwords[i])
我希望顯示字符串中的各個字母。 期望的結果應為“ jtpaarnnaiicccteeice”,但應為“ jtaniceapracticenice”。 由於* nwords給出了存儲在元組中的第一個元素。 我希望* nwords將其擴展為單個字符串。 我怎樣才能做到這一點? 我的意思是,我不一般地知道它可能包含多少個參數。
Q1:為什么不給'practice'作為最大字符串,為什么max(word1,max(t0))給tanice
字符串按字典順序排序。 t
> p
所以tanice
大於practice
問題2:t = max(word1,max(t0))有效,但max(word1,nwords)無效。 為什么&對此有解決方法?
這是因為max
期望可迭代或可變數量的參數。 在后一種情況下, max
嘗試將字符串與列表進行比較,而不是將字符串與列表中的每個元素進行比較。 您可以使用itertools.chain
:
max(chain([word1],nwords),key=len) #assuming you're comparing based on length.
問題3:...
我不太確定您要在這里做什么。 根據描述,您似乎希望將字符串壓縮在一起后將其鏈接起來:
from itertools import chain,izip_longest
''.join(chain.from_iterable(izip_longest(word1,*nwords,fillvalue='')))
這是一個沒有函數的示例:
>>> from itertools import chain,izip_longest
>>> words = ('janice','tanice','practice')
>>> ''.join(chain.from_iterable(izip_longest(*words,fillvalue='')))
'jtpaarnnaiicccteeice'
開箱操作員是雙向的。 您可以使用它說“我希望此函數具有可變數量的位置參數”:
def foo(*args): ...
或者,“我想向此函數傳遞可變數量的位置參數”:
foo(*iterable)
在這里,我使用了第二種形式將可變數量的字符串傳遞給izip_longest
1 ,該字符串需要任意數量的位置參數。
上面的代碼等效於:
''.join(chain.from_iterable(izip_longest('janice','tanice','practice',fillvalue='')))
zip_longest
上的1 zip_longest
zip_longest
>>> max("tanice", "practice")
'tanice'
>>>
您應該比較len(word)
而不是單詞本身!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.