python基础二之列表和元组(序列相加、乘法、成员资格)

版权声明:总想写点东西,打算把以前看的东西在重新看一遍 https://blog.csdn.net/qq_36581957/article/details/83892584

这篇文章记载序列相加、乘法、成员资格等内容。

1、序列相加

看下面的例子:

number1=[1,2,3]
number2=[4,5,6]
add=number1+number2;
print("add:{}".format(add))
str1=["hello"]
str2=["world"]
add2=str1+str2;
add3=number2+str2
print(add2)
print(add3)

输出结果:

add:[1, 2, 3, 4, 5, 6]
['hello', 'world']
[4, 5, 6, 'world']

一般而言,相同类型的序列可以相加,不同的一般不能相加,例如:

str="hello"
number=[1,2,3]
add=str+number
print(add)

来看看输出结果:

Traceback (most recent call last):
  File "D:/Python_test/project2/sequence.py", line 77, in <module>
    add=str+number
TypeError: must be str, not list

 显然,不同类型的序列不能相加。

2、乘法:将这个序列和数x相乘,将重复这个序列x次来创建一个新序列。

a1=[1,2,3,4,5]
a2=a1*3;
str=["hello"]
str2=str*3;
print(a2)
print(str2)

输出结果是:

['hello', 'hello', 'hello']
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

3、成员资格:检索指定的值是否在序列中,可以用关键字in,返回值为布尔型。

permission="hello,world"
xajh=["东方不败","风清扬","令狐冲"]
bool1="hello"in permission;
bool2="python" in permission;
bool3="东方不败" in xajh;
bool4="任我行" in xajh;
print("bool1:{}".format(bool1))
print("bool2:{}".format(bool2))
print("bool3:{}".format(bool3))
print("bool4:{}".format(bool4))

输出结果为:

bool1:True
bool2:False
bool3:True
bool4:False

4、长度、最值

python的内置函数len,min,max分别使用来序列中包含元素的个数,最小值和最大值的。实例如下:

numbers=[2,10,4,8,200]
mins=min(numbers);
maxs=max(numbers);
lens=len(numbers);
print("mins:{}".format(mins))
print("maxs:{}".format(maxs))
print("lens:{}".format(lens))

输出结果如下:

mins:2
maxs:200
lens:5

猜你喜欢

转载自blog.csdn.net/qq_36581957/article/details/83892584
今日推荐