例如,我有一个程序可以添加字母并从列表中删除字母。这是代码:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
do = input("Press 'a' to append and 'r' to remove: ")
if do == 'a':
letter = input("Enter a letter to append: ")
my_list.append(letter)
print (my_list)
elif do == 'r':
letter = input("Enter a letter to append: ")
my_list.remove(letter)
print (my_list)
else:
print ("Something gone wrong...")
要从列表中删除一封信,我必须告诉程序我要做什么,然后它会要求我删除一封信。有没有办法调用我自己的函数(只是为了让它更容易使用程序),如下所示:
def removing(letter):
my_list.remove(letter)
print (my_list)
要在控制台中使用此功能,请执行以下操作:
What are you going to do? removing(b)
答案 0 :(得分:6)
这是一个有些重组的建议。它要求用户输入
附加内容
或
删除某些内容
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
choices = {'remove': my_list.remove,
'append': my_list.append}
print my_list
while True:
try:
choice, item = raw_input('append <x> OR remove <x>\n').split()
choices[choice](item)
except (KeyError, ValueError):
print('something went wrong...')
print my_list
演示:
['a', 'b', 'c', 'd', 'e', 'f']
append <x> OR remove <x>
append z
['a', 'b', 'c', 'd', 'e', 'f', 'z']
append <x> OR remove <x>
remove d
['a', 'b', 'c', 'e', 'f', 'z']
append <x> OR remove <x>
remove y
something went wrong...
['a', 'b', 'c', 'e', 'f', 'z']
这应该会给你一个想法/让你开始。字典很容易扩展。
答案 1 :(得分:3)
为了好玩,您可以将@timgeb的答案扩展为一次接受多个参数。
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
choices = {'remove': my_list.remove,
'append': my_list.append}
def call_choice(name, *args):
for arg in args:
choices[name](arg)
print my_list
while True:
try:
input_string = raw_input('append <x> OR remove <x>\n')
call_choice(*input_string.split())
except (KeyError, ValueError):
print('something went wrong...')
print my_list
演示:
['a', 'b', 'c', 'd', 'e', 'f']
append <x> OR remove <x>
append a b c d e f g
['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove a b c
['d', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove a
['d', 'e', 'f', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove d
['e', 'f', 'b', 'c', 'd', 'e', 'f', 'g']
append <x> OR remove <x>
remove e f b c d e f g
[]