怎么使用python编写一个能把列表内所有元素前面都加一个字符的函数

2023-12-29 16:33:08
推荐回答(5个)
回答1:

1、创建python文件,文件名为:testlistadd.py;

2、编写代码,在原有list的每个元素前面加上字符‘1’;

old_list = ['a','b','c','d']

new_list = ['1'+x for x in old_list]

print(new_list)

3、在窗口中右击,并选择‘在终端中运行Python文件’选项,执行python代码;

4、在‘终端’窗口中,查看执行结果,可以发现满足所需,即在所有元素前面都加了字符串‘1’。

回答2:

l = ['abc','def','xyz']
map(lambda x: 'str_'+x, l);

回答3:

用列表推导式就行
list1 = ['a','b','c','d']
new_list = ['!'+x for x in list1]
print(new_list)

回答4:

def make_great(names):
    for i in range(len(names)):
        names[i]="the great" + names[i]
name_list=['a','b','c']
make_great(name_list)
print(name_list)

回答5:

def make_great(magicians):
    i = 0
    while i < len(magicians):
        magicians[i] = "the Great " + magicians[i]
        i += 1