我正在寻找的是最好的方式,'如果这个列表太短,将它延长到9个元素并添加'选择4','选择5'等作为附加元素.另外,用'Choice x'替换任何'None'元素.也可以替换""和0.
一个示例转换将是
['a','b',None,'c']
Run Code Online (Sandbox Code Playgroud)
至
['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
Run Code Online (Sandbox Code Playgroud)
我的初始代码滥用try/except并且有一个我没注意到的一个一个错误; 感谢joeforker和所有指出的人.根据评论,我尝试了两个同样测试良好的简短解决方案:
def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
Run Code Online (Sandbox Code Playgroud)
和
def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
Run Code Online (Sandbox Code Playgroud)
我认为#2赢得更多pythonic,所以它是我将使用的那个.它易于理解和使用常见的结构.拆分步骤是合乎逻辑的,可以使人们更容易理解.
eph*_*ent 10
不同的是zip
,Python会map
自动扩展更短的序列None
.
map(lambda a, b: b if a is None else a,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
Run Code Online (Sandbox Code Playgroud)
你可以将lambda简化为
map(lambda a, b: a or b,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
Run Code Online (Sandbox Code Playgroud)
如果它没关系在对待其他错误状物体choicesTxt
一样None
.
我最初的反应是将列表扩展和"填充空白"分成不同的部分,如下所示:
for i, v in enumerate(my_list):
my_list[i] = v or "Choice %s" % (i+1)
for j in range(len(my_list)+1, 10):
my_list.append("Choice %s" % (j))
# maybe this is nicer for the extension?
while len(my_list) < 10:
my_list.append("Choice %s" % (len(my_list)+1))
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用这种try...except
方法,就像Douglas所说的那样抓住一个特定的例外.否则,你会抓住一切:KeyboardInterrupts
,RuntimeErrors
,SyntaxErrors
,....你不想那样做.
编辑:修复1索引列表错误 - 谢谢DNS!
编辑:添加替代列表扩展
归档时间: |
|
查看次数: |
3284 次 |
最近记录: |