通过将列表元素传递给函数来修改它们

时间:2015-01-28 16:50:49

标签: python

我正在使用pass-by-reference来更改列表中字符串的大小写。这段代码似乎不起作用:

def test(the_list):
    for word in the_list:
        word.lower()

the_list=["Python", "Programming"]
test(the_list)
print the_list

预期产出:

["python","programming"]

2 个答案:

答案 0 :(得分:3)

这是你想要完成的事情吗?

def test(the_list):
    for i in range(len(the_list)):
        the_list[i] = the_list[i].lower()

the_list=["Python", "Programming"]
test(the_list)
print the_list

答案 1 :(得分:3)

你可以使用for循环来做到这一点,但使用bulit-in列表推导它会更快更可读:

the_list=["Python", "Programming"]
the_list = [x.lower() for x in the_list]
print the_list