向lis的单个项添加字符串

2024-10-02 04:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在列表的最后一项BinList前面加一个字符串less than or equal toBinList有10个项目长

我已经用一个字符串less than在列表中的所有其他项前面加上了我编写的函数:

def prepend(list, string):
    string += '{0}'
    list = [string.format(i) for i in list]
    return (list)

但我不能把它用在单子上

我试过了

lastbin = BinList[10]
string = 'less than or equal to '
FinalCell = string.format(lastbin)

但这只是返回less than or equal to

也不是BinList[10]的数目


Tags: orto项目函数字符串format列表string
2条回答
def prepend(list, string, last_string):
    list[:-1] = [(string + str(i)) for i in list[:-1]]
    list[-1] = last_string + str(list[-1])
    return list

prepend([1, 2, 'tank'], 'less than ', 'less than or equal to ')
# ['less than 1', 'less than 2', 'less than or equal to tank']

不需要循环或任何东西,只需要像第二个例子一样使用切片,但在同一行中简单地赋值。此外,BinList[-1]将访问列表中的最后一个元素:

 BinList[-1] = 'less than or equal to {}'.format(BinList[-1])

您甚至可以使prepend将列表中的最后一个元素与其他元素分开:

BinList = [1, 2, 3]

def prepend(l, string, last):
    length = len(l)
    return [[last, string][i<length-1].format(s) for i, s in enumerate(l)]

print(prepend(BinList, 'equal to {}', 'less than or equal to {}'))

这将返回:

['equal to 1', 'equal to 2', 'less than or equalto 3']

相关问题 更多 >

    热门问题