简体   繁体   English

从列表中的最后一个元素中删除逗号

[英]Removing comma from last element in list

I am trying to return the array of number without the last comma.我试图返回没有最后一个逗号的数字数组。 ex)前任)

[['0,0,0,0,0'], ['1,1,1,1'], ['2,2,2'], ['3,3'], ['4']]

I keep returning this我一直在返回这个

[['0,0,0,0,0,'], ['1,1,1,1,'], ['2,2,2,'], ['3,3,'], ['4,']]

The definiton is as follow:定义如下:

def array(i):
    arraylist = []
    for num in range(0, i):
        arraylist.append([])
        if num is 0:
            print (str(0) + " ") * i
            arraylist[num].append((str(0)) * (i-(num)))
        else:
            print (str(num) + " ") * (i - (num))
            arraylist[num].append((str(num)+",") * (i-(num)))
    return arraylist

Aditionally if you could help me take out the quotations in the returned array.另外,如果您能帮我取出返回数组中的引号。

If by remove the trailing comma and the quotations you mean that you wanna return a list of lists of numbers, this is what your function needs to do:如果通过删除尾随逗号和引号,您的意思是要返回数字列表列表,那么您的函数需要执行以下操作:

def array(i):
    arraylist = []
    for num in range(0, i):
        arraylist.append((i - num) * [num])
    return arraylist

from my shell:从我的外壳:

>>> print array(5)
[[0, 0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2], [3, 3], [4]]

if what you want is what you had before but without the trailing coma, ie a list of lists with one one array inside the inner lists, just remove the last char from each string after building it:如果您想要的是您之前拥有的但没有尾随昏迷的内容,即内部列表中有一个数组的列表列表,只需在构建后从每个字符串中删除最后一个字符:

def array(i):
    arraylist = []
    for num in range(0, i):
        arraylist.append([])
        if num is 0:
            arraylist[num].append((str(0) + ',') * (i-(num)))
        else:
            arraylist[num].append((str(num)+",") * (i-(num)))
        arraylist[num][0] = arraylist[num][0][:-1]
    return arraylist

from my shell:从我的外壳:

>>> print array(5)
[['0, 0, 0, 0, 0'], ['1, 1, 1, 1'], ['2, 2, 2'], ['3, 3'], ['4']]

This works:这有效:

>>> def array(i):
...     l = []
...     for num in xrange(i):
...         l.append([num] * (i - num))
...     return l

Then:然后:

>>> array(5)
[[0, 0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2], [3, 3], [4]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM