序列运算符
本课属于 Coddy Python 学习旅程的“基础知识”单元。第 66 课,共 77 课。
Python 提供了多个可用于列表、字符串和元组等序列的运算符。
使用 + 运算符进行拼接,可以将两个序列连接起来:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2执行上面的代码后,combined_list 中包含:
[1, 2, 3, 4, 5, 6]使用 * 运算符重复序列指定的次数:
numbers = [1, 2, 3]
repeated_numbers = numbers * 3运行上述代码后,repeated_numbers 中包含:
[1, 2, 3, 1, 2, 3, 1, 2, 3]这些运算符也适用于其他序列:
# 字符串拼接
greeting = "Hello" + " " + "World" # "Hello World"
# 字符串重复
stars = "*" * 5 # "*****"挑战
简单创建一个名为 create_pattern 的函数,它接受两个参数:
- 一个数字列表(
numbers)。 - 一个整数(
repeats)。
这个函数应该:
- 将列表与自身拼接(列表 + 列表)。
- 使用
*运算符,将得到的列表重复repeats次。 - 返回最终的模式。
亲手试试
def create_pattern(numbers, repeats):
# 在这里编写你的代码
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Python 在线编译器