Python 2.7 编写函数以复制数据

Python 2.7 编写函数以复制数据,python-2.7,Python 2.7,我正在写一个函数,它接受两个参数,数据是要复制的,时间是数据应该复制的次数。 我是python新手,有人能帮忙吗 def replicate_iter(times, data): output = times * data if type(data) != str: raise ValueError('Invalid') if times <= 0: return [] else: return output.

我正在写一个函数,它接受两个参数,数据是要复制的,时间是数据应该复制的次数。 我是python新手,有人能帮忙吗

def replicate_iter(times, data):
    output = times * data
    if type(data) != str:
        raise ValueError('Invalid')
    if times <= 0:
        return []
    else:
        return output.split(' ')

print replicate_iter(4, '5') #expected output [5, 5, 5, 5]

['5555']
def replicate_iter(时间、数据):
输出=次*数据
如果类型(数据)!=str:
raise VALUERROR('无效')

如果您返回的是
output.split(“”)
,但您的输入
'5'
不包含空格。 因此,
'5555'.split(“”)
返回
['5555']
。您需要更改返回条件或在元素之间添加空格

添加空格:(假设字符串本身不包含空格)

更改返回/函数:(这将支持带空格的字符串)

def replicate_iter(时间、数据):
输出=[]
如果类型(数据)!=str:
raise VALUERROR('无效')
而len(输出)<次:
output.append(数据)
返回输出

此代码将被注释,并将为您提供所需的输出,但使用大小为
次的for循环

def replicate_iter(times, data):
    output = [] #you can initialize your list here
    if type(data) != str:
        raise ValueError('Invalid')
    #if times <= 0: # Since input was initialized earlier
    #    return [] # These two lines become unnecessary
    else:
        for i in range(times): #use a for loop to append to your list
            output.append(int(data)) #coerce data from string to int
        return output #return the list and control to environment

print replicate_iter(4, '5')

具有给定示例输入的
输出
变量不包含空格字符(用于拆分)。
def replicate_iter(times, data):
    output = []
    if type(data) != str:
        raise ValueError('Invalid')
    while len(output) < times:
       output.append(data)
    return output
def replicate_iter(times, data):
    output = [] #you can initialize your list here
    if type(data) != str:
        raise ValueError('Invalid')
    #if times <= 0: # Since input was initialized earlier
    #    return [] # These two lines become unnecessary
    else:
        for i in range(times): #use a for loop to append to your list
            output.append(int(data)) #coerce data from string to int
        return output #return the list and control to environment

print replicate_iter(4, '5')
[5, 5, 5, 5]