向列表元素添加符号

时间:2018-12-22 13:31:13

标签: python

我正在尝试建立列表,并且具有类似如下的列表形式:

numbers=['1','2','3']

我想转化为:

numbers=['-1-','-2-','-3-']

稍后可能需要将其更改为

numbers=['-1-','(2)','-3-']

,我将选择哪个。有什么方法或函数可以做到这一点吗? 。 抱歉,我的英语谢谢!

2 个答案:

答案 0 :(得分:2)

第一种情况是通过列表理解解决的

l = [f'-{n}-' for n in numbers]

此for循环的第二个,类似于先前的列表理解

l = []
for i, n in enumerate(numbers):
    if i % 2 == 0:
        l.append(f'-{n}-')
    else:
        l.append(f'({n})')

或者,您也可以将for循环编写为列表理解

[f'-{n}' if i % 2 == 0  else f'-({n})-' for i, n in enumerate(numbers)]

答案 1 :(得分:0)

尝试使用此功能,它与上一个有所不同,但最终还是相同的:

def formatList(listIn,selections):
    l=[]
    for i in range(len(listIn)):
        if not i in selections:
            l.append('-'+str(listIn[i])+'-')
        else:
            l.append('('+str(listIn[i])+')')
    return l

其中选择作为输入将类似于[2,'''other selections'''](如果您不知道,'''This is a comment in python (so is this #blahblah but it has to be on the same line)'''