简体   繁体   English

Python:使用解包星号参数从元组解包单个字符串

[英]Python: Unpack individual strings from tuple using Unpacking asterisk argument

In the following code, I am trying to create a new word by iterating over all words fed as arguments of varying length, string type. 在以下代码中,我试图通过遍历作为长度和字符串类型不同的参数输入的所有单词来创建一个新单词。 I read here * operator makes it non keyword optional arguments. 我在这里阅读*运算符使它成为非关键字可选参数。

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

OUtput: 输出:

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: Instead of giving 'practice'as max string why is max(word1,max(t0)) giving tanice? Q1:为什么不给“练习”作为最大字符串,为什么给max(word1,max(t0))提供tanice?

Q2: t=max(word1,max(t0)) works but max(word1,nwords) doesn't. 问题2:t = max(word1,max(t0))有效,但max(word1,nwords)无效。 Why & Is there a workaround to this? 为什么&对此有解决方法?

Q3: In new_word=new_word+(word1[i]+nwords[i]) I want individual letters in strings to show up. 问题3:在new_word=new_word+(word1[i]+nwords[i])我希望显示字符串中的各个字母。 Desired result should be 'jtpaarnnaiicccteeice' but is 'jtaniceapracticenice'. 期望的结果应为“ jtpaarnnaiicccteeice”,但应为“ jtaniceapracticenice”。 due to * nwords gives the first element stored in tuple. 由于* nwords给出了存储在元组中的第一个元素。 I want *nwords to expand it to individual strings. 我希望* nwords将其扩展为单个字符串。 How can I do that? 我怎样才能做到这一点? My point being, I don't know in a generic sense how many arguments it may take in. 我的意思是,我不一般地知道它可能包含多少个参数。

Q1: Instead of giving 'practice' as max string why is max(word1,max(t0)) giving tanice Q1:为什么不给'practice'作为最大字符串,为什么max(word1,max(t0))给tanice

Strings are ordered lexicographically. 字符串按字典顺序排序。 t > p so tanice is greater than practice t > p所以tanice大于practice

Q2: t=max(word1,max(t0)) works but max(word1,nwords) doesn't. 问题2:t = max(word1,max(t0))有效,但max(word1,nwords)无效。 Why & Is there a workaround to this? 为什么&对此有解决方法?

This is because max expects either an iterable, or a variable number of arguments. 这是因为max期望可迭代或可变数量的参数。 In the latter case, max is trying to compare a string to a list rather than a string to each element in the list. 在后一种情况下, max尝试将字符串与列表进行比较,而不是将字符串与列表中的每个元素进行比较。 You could use itertools.chain : 您可以使用itertools.chain

max(chain([word1],nwords),key=len)  #assuming you're comparing based on length.

Q3: ... 问题3:...

I'm not really sure what you're going for here. 我不太确定您要在这里做什么。 Based on the description, it looks like you want to chain the strings after zipping them together: 根据描述,您似乎希望将字符串压缩在一起后将其链接起来:

from itertools import chain,izip_longest
''.join(chain.from_iterable(izip_longest(word1,*nwords,fillvalue='')))

Here's an example without the function: 这是一个没有函数的示例:

>>> from itertools import chain,izip_longest
>>> words = ('janice','tanice','practice')
>>> ''.join(chain.from_iterable(izip_longest(*words,fillvalue='')))
'jtpaarnnaiicccteeice'

The unpacking operator goes both ways. 开箱操作员是双向的。 You can use it to say "I want this function to have a variable number of positional arguments": 您可以使用它说“我希望此函数具有可变数量的位置参数”:

def foo(*args): ...

Or, "I want to pass this function a variable number of positional arguments": 或者,“我想向此函数传递可变数量的位置参数”:

foo(*iterable)

Here I've used the second form to pass a variable number of strings to izip_longest 1 which takes an arbitrary number of positional arguments. 在这里,我使用了第二种形式将可变数量的字符串传递给izip_longest 1 ,该字符串需要任意数量的位置参数。

The above code is equivalent to: 上面的代码等效于:

''.join(chain.from_iterable(izip_longest('janice','tanice','practice',fillvalue='')))

1 zip_longest on python3.x zip_longest上的1 zip_longest zip_longest

>>> max("tanice", "practice")
'tanice'
>>>

You should compare on len(word) not the word itself! 您应该比较len(word)而不是单词本身!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM