【发布时间】:2013-05-01 12:22:08
【问题描述】:
在下面的代码中,我试图通过迭代作为不同长度、字符串类型的参数提供的所有单词来创建一个新单词。我在这里读到 * 运算符使其成为非关键字可选参数。
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)) 不提供 'practice' 作为最大字符串,而是提供 tanice?
Q2:t=max(word1,max(t0)) 有效,但 max(word1,nwords) 无效。为什么以及是否有解决方法?
Q3:在new_word=new_word+(word1[i]+nwords[i]) 中,我希望显示字符串中的单个字母。期望的结果应该是“jtpaarnnaiicccteeice”,但应该是“jtaniceapracticenice”。
由于 * nwords 给出了存储在元组中的第一个元素。我希望 *nwords 将其扩展为单个字符串。我怎样才能做到这一点?我的意思是,我不知道一般意义上它可能包含多少参数。
【问题讨论】:
-
您是否试图找到 A) 可以使用传递给函数的单词中的部分/所有字母来构建的单词,即传入
he和root,返回的一个值将是 @987654327 @。 AND/OR B) 从字面上尝试将单词组合成一个更大的单词:传入sled和dog将得到sleddog。 -
使用
max,您不是在比较长度,而是比较词汇位置(t 在字母表中p 之后)。因此tanice > practice。示例:print max('hello', 'goodbye')给出hello。 -
我很难看到你真正想要回到这里的是什么。你能详细说明一下吗?也许我们可以想出一个更优雅的方式来做到这一点。