列表的练习
1.求列表的最大数和下标
nums = [3, 1, 9, 8, 4, 2, 0, 7, 5]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums[0])
x = nums[0] # 假设第0个是最大数
index = 0
for num in nums:
if num > x: # 如果发现列表里存在比假设还要大的数字
# 说明假设不成立,把假设的值设置为发现的数字
x = num
print('发现的最大数是%d' % x)
i = 0
while i < len(nums):
if nums[i] > x:
x = nums[i]
index = i
i += 1
print('发现的最大数是%d,它的下标是%d' % (x, index))
2.删除列表里的空字符串
words = ['hello', 'good', '', '', 'yes', 'ok', '']
# x = ['hello','good','yes','ok']
# 在使用for...in 循环遍历列表时,最好不要对元素进行增删操作
# for word in words:
# if word == '':
# words.remove(word)
# print(words)
# i = 0
# while i < len(words):
# if words[i] == '':
# words.remove(words[i])
# i -= 1
# i += 1
# print(words)
words2 = []
for word in words:
if word != '':
words2.append(word)
print(words)
版权声明:本文为weixin_50077855原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。