Python 用repeat()重复单个值

  • Post category:Python

当我们需要多次重复一个固定的值时,可以使用Python中的repeat()函数,该函数可以传入两个参数,第一个参数是要重复的值,第二个参数是重复的次数。

下面是repeat()函数的基本语法:

repeat(value, times)

其中,value表示要重复的值,times表示重复的次数。

下面是两个使用repeat()函数的示例:

示例1:重复字符串

from itertools import repeat

# 将'hello'字符串重复3次
result = list(repeat('hello', 3))
print(result)

输出结果为:

['hello', 'hello', 'hello']

上述示例中,首先我们通过from itertools import repeat的方式导入repeat函数,接着使用list()函数将repeat()返回的迭代器转换成列表输出。这里我们将'hello'字符串重复了3次。

示例2:重复自定义的数据结构

from itertools import repeat

# 自定义Person类
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} - {self.age}"

# 创建Person对象并重复3次
p = Person('Alice', 25)
result = list(repeat(p, 3))
for r in result:
    print(r)

输出结果为:

Alice - 25
Alice - 25
Alice - 25

上述示例中,我们自定义了Person类来表示一个人,这个类包含nameage两个属性,以及一个__str__方法用于输出信息。接着我们使用repeat()函数将一个Person对象重复了3次,并使用for循环输出每个重复的对象。

使用repeat()函数可以有效的提高代码的复用性和可读性,尤其是对于需要多次使用一个固定值的场景非常实用。