90 lines
2.3 KiB
Python
90 lines
2.3 KiB
Python
# Python的负索引是一种用于从序列(如列表、元组、字符串等)末尾倒数访问元素的方式。负索引从 -1 开始,表示序列的最后一个元素;-2 表示倒数第二个元素,以此类推。它使得我们更方便地访问序列末尾的元素,而不需要手动计算序列的长度。
|
|
|
|
|
|
# 定义一个列表用于演示
|
|
data = ["A", "B", "C", "D", "E", "F", "G"]
|
|
|
|
# for i in range(len(data)):
|
|
# print(f"data[{i}] = {data[i]}")
|
|
|
|
# 负索引
|
|
for i in range(-1, -len(data) - 1, -1):
|
|
print(f"data[{i}]={data[i]}")
|
|
|
|
|
|
# 应用
|
|
# 使用len和负索引
|
|
items = ["apple", "banana", "cherry", "date", "elderberry"]
|
|
for i in range(-1, -len(items) - 1, -1):
|
|
print(f"{i}:{items[i]}")
|
|
|
|
# 使用reversed
|
|
# 翻转列表
|
|
for item in reversed(items):
|
|
print(item)
|
|
|
|
# 使用切片
|
|
reversed_items = items[::-1]
|
|
print(reversed_items)
|
|
|
|
|
|
# 反向遍历
|
|
reversed_arr = []
|
|
for index, item in enumerate(items):
|
|
last_index = len(items) - 1 - index
|
|
reversed_arr.append(items[last_index])
|
|
# print(last_index)
|
|
print(f"{items[last_index]}")
|
|
|
|
print("\n=== 反向遍历 ===")
|
|
print(reversed_arr)
|
|
|
|
# 在算法中的应用
|
|
|
|
# 判断是否是回文数
|
|
|
|
|
|
def is_palindrome(text=""):
|
|
text = text.lower().replace(" ", "")
|
|
length = len(text) // 2
|
|
for i in range(length):
|
|
if text[i] != text[-(i + 1)]:
|
|
return False
|
|
return True
|
|
|
|
|
|
test_strings = ["racecar", "hello", "A man a plan a canal Panama", "python"]
|
|
|
|
for s in test_strings:
|
|
result = is_palindrome(s)
|
|
print(f"{s}:{result}")
|
|
|
|
|
|
# 使用负索引实现数组旋转
|
|
# 在实际算法开发中,负索引可用来优雅地解决列表、字符串、数组等序列相关的问题。
|
|
def rotate_array(arr, k):
|
|
"""
|
|
将数组向右旋转k个位置
|
|
例如: [1, 2, 3, 4, 5] 右旋1位 -> [5, 1, 2, 3, 4]
|
|
"""
|
|
k = k % len(arr)
|
|
return arr[-k:] + arr[:-k]
|
|
|
|
|
|
print("\n=== 数组旋转演示 ===")
|
|
test_array = [1, 2, 3, 4, 5]
|
|
for k in [1, 2, 3]:
|
|
rotate = rotate_array(test_array, k)
|
|
print(f"向右旋转{k}位:{rotate}")
|
|
|
|
# arr[-k:] 取出最后k个元素(右侧)
|
|
# arr[:-k] 取出前面剩余的元素(左侧)
|
|
# 拼接即可得到右旋后的新数组
|
|
|
|
#
|
|
path = "/home/user/documents/file.txt"
|
|
extension = path.split("/")[-1]
|
|
print(extension)
|
|
abc = extension.split(".")[-1]
|
|
print(abc)
|