day2---列表处理(python一天一学)

test = [1, 2, 3, 4, 5, 'a', 'b', 'c']
test1 = 'kjhgfdsuytreaa'

# 索引取值
print(test[1])
print(test[1:3])

# for循环取值
for i in range(len(test)):
print(test[i])

# 字符串转化列表
print(list(test1))
str1 = "hi hello world"
print(str1.split(" "))

# 列表转化字符串,里边不能有数字
l = ["hi", "hello", "world"]
print(" ".join(l))

# 追加元素
test.append(1)
print(test)

# 浅拷贝
a = test.copy()
print(a)

# 计算列表元素的出现次数
print(test.count(1))

# 列表追加迭代
test.extend(test1)
print(test)

# 获取元素索引,左优先
print(test.index('a', 1, 6))

# 固定索引位置插入
test.insert(1, 'a')
print(test)

# 1.删除元素,pop返回移除的元素,不传index时候默认删除最后的值
print(test.pop(0))
print(test)

# 2.删除元素,删除指定值,左优先
test.remove('a')
print(test)

# 列表反转
test.reverse()
print(test)

# 列表排序
paixu = [4, 1, 5, 6, 3, 2]
# 升序
paixu.sort()
print(paixu)
# 降序
paixu.sort(reverse=True)
print(paixu)

# 字符串通过索引可取值,但是不可以修改;列表可以通过索引取值也可以通过索引赋值

猜你喜欢

转载自www.cnblogs.com/hahagaga/p/9591056.html