大多数用python语言扩展潜在不完整列表的方法

时间:2022-03-16 22:08:18

What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.

我寻找的是最好的表达方式,“如果这个列表太短,把它延长到9个元素,并添加“选项4”、“选项5”等作为附加元素。同样,用“选项x”替换任何“无”元素。“替换”和“0”也是可以的。

An example transformation would be

一个例子就是变换

['a','b',None,'c']

to

['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']

My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:

我最初的代码滥用了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)

and

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))

I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.

我认为#2赢的更像python,所以这是我要用的。它很容易理解并使用公共结构。拆分步骤是合乎逻辑的,而且会让人一眼就能理解。

20 个解决方案

#1


10  

Unlike zip, Python's map automatically extends shorter sequences with None.

与zip不同的是,Python的map自动扩展不包含任何内容的更短的序列。

map(lambda a, b: b if a is None else a,
    choicesTxt,
    ['Choice %i' % n for n in range(1, 10)])

You could simplify the lambda to

可以化简为

map(lambda a, b: a or b,
    choicesTxt,
    ['Choice %i' % n for n in range(1, 10)])

if it's okay to treat other false-like objects in choicesTxt the same as None.

如果可以将choicesTxt中的其他伪类对象视为None。

#2


7  

My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so:

我最初的反应是将列表的扩展和“填充”分成几个部分:

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))

If you do stick with the try...except approach, do catch a specific exception as Douglas shows. Otherwise, you'll catch everything: KeyboardInterrupts, RuntimeErrors, SyntaxErrors, ... . You do not want to do that.

如果你坚持尝试……除了方法,请捕获一个特定的异常,如Douglas所示。否则,您将捕获所有内容:KeyboardInterrupts、runtimeerror、SyntaxErrors,…。你不想那样做。

EDIT: fixed 1-indexed list error - thanks DNS!

编辑:修复1索引列表错误-感谢DNS!

EDIT: added alternative list extension

编辑:添加可选列表扩展名

#3


3  

I think I'd do something pretty much like that, but with a few tidy ups:

我想我会做一些类似的事情,但是有一些整理:

for i in range(0,10):
  try:
    if choicesTxt[i] is None:
      choicesTxt[i] = "Choice %d"%i
  except IndexError:
    choicesTxt.append("Choice %d"%i)

Of which the only important two are to only catch IndexError rather than any exception, and to index from 0.

其中唯一重要的两个是只捕获IndexError而不是任何异常,以及从0开始索引。

And the only real problem with the original would be if choicesTxt is empty, when the choices added will be off by one.

而原选项唯一的问题是如果choicesTxt是空的,那么添加的选项将被删除。

#4


3  

You could use map (dictionary) instead of list:

你可以使用地图(字典)代替列表:

choices_map = {1:'Choice 1', 2:'Choice 2', 3:'Choice 12'}
for key in xrange(1, 10):
    choices_map.setdefault(key, 'Choice %d'%key)

Then you have map filled with your data.
If you want a list instead you can do:

然后你的地图上填满了你的数据。如果你想要一个清单,你可以:

choices = choices_map.values()
choices.sort() #if you want your list to be sorted
#In Python 2.5 and newer you can do:
choices = [choices_map[k] for k in sorted(choices_map)]

#5


2  

I think you should treat resizing the array as a separate step. To do so, in the case the array is too short, call choicesTxt=choicesTxt+[None]*(10-len(choicesTxt)). The None choice reasignment can be done using list comprehensions.

我认为您应该将调整数组大小作为单独的步骤。为此,在数组太短的情况下,调用choicesTxt=choicesTxt+[None]*(10-len(choicesTxt))。没有选择重新分配可以使用列表的理解。

#6


2  

Simplest and most pythonic for me is:

对我来说最简单也是最python化的是:

repl = lambda i: "Choice %d" % (i + 1) # DRY
print ([(x or repl(i)) for i, x in enumerate(aList)]
     + [repl(i) for i in xrange(len(aList), 9)])

#7


1  

I'm a little unclear about why you're using range(1, 10); since you're using choicesTxt[i], that ends up skipping the None check for the first element in your list.

我不太清楚你为什么使用range(1,10);由于您使用的是choicesTxt[i],因此最终会跳过清单中第一个元素的None检查。

Also, there are obviously easier ways to do this if you're creating a new list, but you're asking specifically to add to an existing list.

此外,如果您正在创建一个新列表,那么显然有更简单的方法来实现这一点,但是您需要特别地向现有列表添加内容。

I don't think this is really cleaner or faster, but it's a different idea for you to think about.

我不认为这更简洁或更快,但这是一个不同的想法。

for i, v in enumerate(choicesTxt):
    choicesTxt[i] = v or "Choice " + str(i + 1)

choicesTxt.extend([ "Choice " + str(i) for i in range(len(choicesTxt) + 1, 10) ])

#8


1  

What about that (seems to be a dict -- not a list -- when it's incomplete)

那(似乎是一个命令,而不是一个列表——当它不完整的时候)

a = {1:'a', 2:None, 5:'e'} #test data
[a[x] if x in a and a[x] is not None else 'Choice %d'%x for x in xrange(1,10)]

Edit once more: If it's really a list (not a dict):

再编辑一次:如果它真的是一个列表(不是一个命令):

b=['a',None,'b']
[b[x] if len(b)>x and b[x] is not None else 'Choice %d'%x for x in xrange(10)]

needs Python 2.5 I think (because of the ternary operator)?

我认为需要Python 2.5(因为三元运算符)?

(Thanks to joeforker fixed that it uses keys 1 to 10 and not 0 to 10 anymore; thanks to SilentGhost: in is more pythonic than has_key() or len())

(感谢joeforker修复,它使用的键是1到10,而不是0到10;多亏了SilentGhost: in比has_key()或len()更具有python性

#9


1  

I would do

我要做

for i, c in enumerate(choices):
    if c is None:
        choices[i] = 'Choice X'

choices += ['Choice %d' % (i+1) for i in range(len(choices), 10)]

which only replaces actual None values (not anything that evaluates as false), and extends the list in a separated step which I think is clearer.

它只替换实际的None值(不是计算为false的值),并以一个单独的步骤扩展列表,我认为这样更清楚。

#10


1  

I find that when list comprehensions get long it's better to just use a standard for loop. Nearly the same as others but anyway:

我发现当列表理解变长时,最好使用循环标准。几乎和其他人一样,但无论如何:

>>> in_list = ["a","b",None,"c"]
>>> full_list = in_list + ([None] * (10 - len(in_list)))
>>> for idx, value in enumerate(full_list):
...     if value == None:
...             full_list[idx] = 'Choice %d' % (idx + 1)
...
>>> full_list
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9', 'Choice 10']

#11


1  

choices[:] = ([{False: x, True: "Choice %d" % (i + 1)}[x is None] for i, x in enumerate(choices)] +
  ["Choice %d" % (i + 1) for i in xrange(len(choices), 9)])

#12


1  

You could go simpler with a list comprehension:

你可以通过列表理解更简单:

extendedChoices = choices + ([None] * (10 - len(choices)))
newChoices = ["Choice %d" % (i+1) if x is None else x
    for i, x in enumerate(extendedChoices)]

This appends None to your choices list until it has at least 10 items, enumerates through the result, and inserts "Choice X" if the Xth element is missing.

这将在您的选择列表中添加None,直到它至少包含10个项,并通过结果枚举,并在第Xth元素缺失时插入“选项X”。

#13


1  

If you don't mind replacing anything that evaluates to False with "Choice %d", then result works for Python 2.4.

如果您不介意用“选择%d”替换任何计算值为False的内容,那么result对于Python 2.4是有效的。

If you do mind and have Python 2.5 and above then use result2_5_plus with the power of ternary if.

如果您不介意使用Python 2.5或更高的级别,那么使用result2_5_plus,其幂次为三元If。

If you don't like or can't use ternary if, then take advantage of the fact that True == 1 and False == 0, using the result of x is None to index a list.

如果您不喜欢或不能使用三元If,那么利用True == 1和False == 0这一事实,使用x的结果为None来索引列表。

x = ["Blue", None, 0, "", "No, Yelloooow!"]
y = [None]*9

result = [(t or "Choice %d" % (i+1))\ 
        for i, t in enumerate(x + y[len(x):])]

result2_5_plus = [(t if t is not None else "Choice %d" % (i+1))\ 
        for i, t in enumerate(x + y[len(x):])]

result_no_ternary_if = [[t, "Choice %d" % (i+1)][t is None]\
    for i, t in enumerate(x + y[len(x):])]

['Blue', 'Choice 2', 'Choice 3', 'Choice 4', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
['Blue', 'Choice 2', 0, '', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

#14


1  

def choice_n(index):
  return "Choice %d" % (index + 1)

def add_choices(lst, length, default=choice_n):
  """
  >>> add_choices(['a', 'b', None, 'c'], 9)
  ['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
  """

  for i, v in enumerate(lst):
    if v is None:
      lst[i] = default(i)

  for i in range(len(lst), length):
    lst.append(default(i))

  return lst

if __name__ == "__main__":
  import doctest
  doctest.testmod()

#15


1  

Well in one line:

在一行:

[a or 'Choice %d' % i for a,i in map(None,["a","b",None,"c"],range(10))]

Though that will replace anything that evaluates to False (e.g. None, '', 0 etc) with "Choice n". Best to replace the "a or 'Choice %d' % i" with a function if yuo don't want that.

尽管这将用“选项n”替换计算结果为False(例如None, 0等)的任何内容。如果您不想要,最好将“a或'Choice %d' % i”替换为函数。

The key thing is that map with an argument of None can be used to extend the list to the length needed with None in the required places.

关键的一点是,具有None参数的映射可以用于将列表扩展到所需的长度,而在所需的位置中不包含None。

A tidier (more pythonic) version would be:

一个更整洁(更符合python语言)的版本是:


def extend_choices(lst,length):
    def replace_empty(value,index):
        if value is None:
            return 'Choice %d' % index
        return value
    return [replace_empty(value,index) for value,index in map(None,lst,range(length))]

#16


0  

I would also recommend using xrange instead of range. The xrange function generates the numbers as needed. Range generates them in advance. For small sets it doesn't make much difference, but for large ranges the savings can be huge.

我还建议使用xrange而不是range。xrange函数根据需要生成数字。范围可以提前生成它们。对于小的集合来说没有多大区别,但是对于大的范围来说,节省的钱是巨大的。

#17


0  

>>> in_list = ["a","b",None,"c"]
>>> new = ['choice ' + str(i + 1) if j is None else j for i, j in enumerate(in_list)]
>>> new.extend(('choice ' +str(i + 1) for i in range(len(new), 9)))
>>> new
['a', 'b', 'choice 3', 'c', 'choice 5', 'choice 6', 'choice 7', 'choice 8', 'choice 9']

#18


0  

My two cents...

我的两个美分…

def extendchoices(clist):
    clist.extend( [None]*(9-len(clist)) )
    for i in xrange(9):
        if clist[i] is None: clist[i] = "Choice %d"%(i+1) 

#19


0  

If it's ok to replace any false value, eg '' or 0

如果可以替换任何假值,如"或0

>>> mylist = ['a','b',None,'c']
>>> map(lambda a,b:a or "Choice %s"%b, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

If you really can only replace for None

如果你真的只能用零替换

>>> map(lambda a,b:"Choice %s"%b if a is None else a, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

#20


0  

>>> my_list=['a','b',None,'c']
>>> map (lambda x,y:x or 'Choice {}'.format(y+1),my_list,range(9))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

#1


10  

Unlike zip, Python's map automatically extends shorter sequences with None.

与zip不同的是,Python的map自动扩展不包含任何内容的更短的序列。

map(lambda a, b: b if a is None else a,
    choicesTxt,
    ['Choice %i' % n for n in range(1, 10)])

You could simplify the lambda to

可以化简为

map(lambda a, b: a or b,
    choicesTxt,
    ['Choice %i' % n for n in range(1, 10)])

if it's okay to treat other false-like objects in choicesTxt the same as None.

如果可以将choicesTxt中的其他伪类对象视为None。

#2


7  

My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so:

我最初的反应是将列表的扩展和“填充”分成几个部分:

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))

If you do stick with the try...except approach, do catch a specific exception as Douglas shows. Otherwise, you'll catch everything: KeyboardInterrupts, RuntimeErrors, SyntaxErrors, ... . You do not want to do that.

如果你坚持尝试……除了方法,请捕获一个特定的异常,如Douglas所示。否则,您将捕获所有内容:KeyboardInterrupts、runtimeerror、SyntaxErrors,…。你不想那样做。

EDIT: fixed 1-indexed list error - thanks DNS!

编辑:修复1索引列表错误-感谢DNS!

EDIT: added alternative list extension

编辑:添加可选列表扩展名

#3


3  

I think I'd do something pretty much like that, but with a few tidy ups:

我想我会做一些类似的事情,但是有一些整理:

for i in range(0,10):
  try:
    if choicesTxt[i] is None:
      choicesTxt[i] = "Choice %d"%i
  except IndexError:
    choicesTxt.append("Choice %d"%i)

Of which the only important two are to only catch IndexError rather than any exception, and to index from 0.

其中唯一重要的两个是只捕获IndexError而不是任何异常,以及从0开始索引。

And the only real problem with the original would be if choicesTxt is empty, when the choices added will be off by one.

而原选项唯一的问题是如果choicesTxt是空的,那么添加的选项将被删除。

#4


3  

You could use map (dictionary) instead of list:

你可以使用地图(字典)代替列表:

choices_map = {1:'Choice 1', 2:'Choice 2', 3:'Choice 12'}
for key in xrange(1, 10):
    choices_map.setdefault(key, 'Choice %d'%key)

Then you have map filled with your data.
If you want a list instead you can do:

然后你的地图上填满了你的数据。如果你想要一个清单,你可以:

choices = choices_map.values()
choices.sort() #if you want your list to be sorted
#In Python 2.5 and newer you can do:
choices = [choices_map[k] for k in sorted(choices_map)]

#5


2  

I think you should treat resizing the array as a separate step. To do so, in the case the array is too short, call choicesTxt=choicesTxt+[None]*(10-len(choicesTxt)). The None choice reasignment can be done using list comprehensions.

我认为您应该将调整数组大小作为单独的步骤。为此,在数组太短的情况下,调用choicesTxt=choicesTxt+[None]*(10-len(choicesTxt))。没有选择重新分配可以使用列表的理解。

#6


2  

Simplest and most pythonic for me is:

对我来说最简单也是最python化的是:

repl = lambda i: "Choice %d" % (i + 1) # DRY
print ([(x or repl(i)) for i, x in enumerate(aList)]
     + [repl(i) for i in xrange(len(aList), 9)])

#7


1  

I'm a little unclear about why you're using range(1, 10); since you're using choicesTxt[i], that ends up skipping the None check for the first element in your list.

我不太清楚你为什么使用range(1,10);由于您使用的是choicesTxt[i],因此最终会跳过清单中第一个元素的None检查。

Also, there are obviously easier ways to do this if you're creating a new list, but you're asking specifically to add to an existing list.

此外,如果您正在创建一个新列表,那么显然有更简单的方法来实现这一点,但是您需要特别地向现有列表添加内容。

I don't think this is really cleaner or faster, but it's a different idea for you to think about.

我不认为这更简洁或更快,但这是一个不同的想法。

for i, v in enumerate(choicesTxt):
    choicesTxt[i] = v or "Choice " + str(i + 1)

choicesTxt.extend([ "Choice " + str(i) for i in range(len(choicesTxt) + 1, 10) ])

#8


1  

What about that (seems to be a dict -- not a list -- when it's incomplete)

那(似乎是一个命令,而不是一个列表——当它不完整的时候)

a = {1:'a', 2:None, 5:'e'} #test data
[a[x] if x in a and a[x] is not None else 'Choice %d'%x for x in xrange(1,10)]

Edit once more: If it's really a list (not a dict):

再编辑一次:如果它真的是一个列表(不是一个命令):

b=['a',None,'b']
[b[x] if len(b)>x and b[x] is not None else 'Choice %d'%x for x in xrange(10)]

needs Python 2.5 I think (because of the ternary operator)?

我认为需要Python 2.5(因为三元运算符)?

(Thanks to joeforker fixed that it uses keys 1 to 10 and not 0 to 10 anymore; thanks to SilentGhost: in is more pythonic than has_key() or len())

(感谢joeforker修复,它使用的键是1到10,而不是0到10;多亏了SilentGhost: in比has_key()或len()更具有python性

#9


1  

I would do

我要做

for i, c in enumerate(choices):
    if c is None:
        choices[i] = 'Choice X'

choices += ['Choice %d' % (i+1) for i in range(len(choices), 10)]

which only replaces actual None values (not anything that evaluates as false), and extends the list in a separated step which I think is clearer.

它只替换实际的None值(不是计算为false的值),并以一个单独的步骤扩展列表,我认为这样更清楚。

#10


1  

I find that when list comprehensions get long it's better to just use a standard for loop. Nearly the same as others but anyway:

我发现当列表理解变长时,最好使用循环标准。几乎和其他人一样,但无论如何:

>>> in_list = ["a","b",None,"c"]
>>> full_list = in_list + ([None] * (10 - len(in_list)))
>>> for idx, value in enumerate(full_list):
...     if value == None:
...             full_list[idx] = 'Choice %d' % (idx + 1)
...
>>> full_list
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9', 'Choice 10']

#11


1  

choices[:] = ([{False: x, True: "Choice %d" % (i + 1)}[x is None] for i, x in enumerate(choices)] +
  ["Choice %d" % (i + 1) for i in xrange(len(choices), 9)])

#12


1  

You could go simpler with a list comprehension:

你可以通过列表理解更简单:

extendedChoices = choices + ([None] * (10 - len(choices)))
newChoices = ["Choice %d" % (i+1) if x is None else x
    for i, x in enumerate(extendedChoices)]

This appends None to your choices list until it has at least 10 items, enumerates through the result, and inserts "Choice X" if the Xth element is missing.

这将在您的选择列表中添加None,直到它至少包含10个项,并通过结果枚举,并在第Xth元素缺失时插入“选项X”。

#13


1  

If you don't mind replacing anything that evaluates to False with "Choice %d", then result works for Python 2.4.

如果您不介意用“选择%d”替换任何计算值为False的内容,那么result对于Python 2.4是有效的。

If you do mind and have Python 2.5 and above then use result2_5_plus with the power of ternary if.

如果您不介意使用Python 2.5或更高的级别,那么使用result2_5_plus,其幂次为三元If。

If you don't like or can't use ternary if, then take advantage of the fact that True == 1 and False == 0, using the result of x is None to index a list.

如果您不喜欢或不能使用三元If,那么利用True == 1和False == 0这一事实,使用x的结果为None来索引列表。

x = ["Blue", None, 0, "", "No, Yelloooow!"]
y = [None]*9

result = [(t or "Choice %d" % (i+1))\ 
        for i, t in enumerate(x + y[len(x):])]

result2_5_plus = [(t if t is not None else "Choice %d" % (i+1))\ 
        for i, t in enumerate(x + y[len(x):])]

result_no_ternary_if = [[t, "Choice %d" % (i+1)][t is None]\
    for i, t in enumerate(x + y[len(x):])]

['Blue', 'Choice 2', 'Choice 3', 'Choice 4', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
['Blue', 'Choice 2', 0, '', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

#14


1  

def choice_n(index):
  return "Choice %d" % (index + 1)

def add_choices(lst, length, default=choice_n):
  """
  >>> add_choices(['a', 'b', None, 'c'], 9)
  ['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
  """

  for i, v in enumerate(lst):
    if v is None:
      lst[i] = default(i)

  for i in range(len(lst), length):
    lst.append(default(i))

  return lst

if __name__ == "__main__":
  import doctest
  doctest.testmod()

#15


1  

Well in one line:

在一行:

[a or 'Choice %d' % i for a,i in map(None,["a","b",None,"c"],range(10))]

Though that will replace anything that evaluates to False (e.g. None, '', 0 etc) with "Choice n". Best to replace the "a or 'Choice %d' % i" with a function if yuo don't want that.

尽管这将用“选项n”替换计算结果为False(例如None, 0等)的任何内容。如果您不想要,最好将“a或'Choice %d' % i”替换为函数。

The key thing is that map with an argument of None can be used to extend the list to the length needed with None in the required places.

关键的一点是,具有None参数的映射可以用于将列表扩展到所需的长度,而在所需的位置中不包含None。

A tidier (more pythonic) version would be:

一个更整洁(更符合python语言)的版本是:


def extend_choices(lst,length):
    def replace_empty(value,index):
        if value is None:
            return 'Choice %d' % index
        return value
    return [replace_empty(value,index) for value,index in map(None,lst,range(length))]

#16


0  

I would also recommend using xrange instead of range. The xrange function generates the numbers as needed. Range generates them in advance. For small sets it doesn't make much difference, but for large ranges the savings can be huge.

我还建议使用xrange而不是range。xrange函数根据需要生成数字。范围可以提前生成它们。对于小的集合来说没有多大区别,但是对于大的范围来说,节省的钱是巨大的。

#17


0  

>>> in_list = ["a","b",None,"c"]
>>> new = ['choice ' + str(i + 1) if j is None else j for i, j in enumerate(in_list)]
>>> new.extend(('choice ' +str(i + 1) for i in range(len(new), 9)))
>>> new
['a', 'b', 'choice 3', 'c', 'choice 5', 'choice 6', 'choice 7', 'choice 8', 'choice 9']

#18


0  

My two cents...

我的两个美分…

def extendchoices(clist):
    clist.extend( [None]*(9-len(clist)) )
    for i in xrange(9):
        if clist[i] is None: clist[i] = "Choice %d"%(i+1) 

#19


0  

If it's ok to replace any false value, eg '' or 0

如果可以替换任何假值,如"或0

>>> mylist = ['a','b',None,'c']
>>> map(lambda a,b:a or "Choice %s"%b, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

If you really can only replace for None

如果你真的只能用零替换

>>> map(lambda a,b:"Choice %s"%b if a is None else a, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']

#20


0  

>>> my_list=['a','b',None,'c']
>>> map (lambda x,y:x or 'Choice {}'.format(y+1),my_list,range(9))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']