📜  Python – Uni 长度切片和访问表示法之间的区别

📅  最后修改于: 2022-05-13 01:54:22.992000             🧑  作者: Mango

Python – Uni 长度切片和访问表示法之间的区别

提取元素的方法有很多种,其中包括 Uni length slicing 和 Access Notations。让我们检查一下它们之间的区别。

差异#1:不同容器的不同行为

访问表示法返回 List 和 Strings 中的元素,但在使用 uni 长度切片和元素的情况下进行切片时返回 1 长度的字符串字符串。

Python3
# Python3 code to demonstrate working of 
# Difference between Uni length slicing and Access Notation
# In different containers
  
# initializing lists
test_list = [5, 7, 2, 6, 8, 1]
  
# initializing string 
test_str = "572681"
  
# printing original list
print("The original list : " + str(test_list))
  
# printing string
print("The original string : " + str(test_str))
print("\r")
  
# access Notation results 
acc_list = test_list[3]
acc_str = test_str[3]
  
# unilength slicing results 
slc_list = test_list[3 : 4]
slc_str = test_str[3 : 4]
  
# printing results 
print("The access notation result for list : " + str(acc_list))
print("The access notation result for string : " + str(acc_str))
print("\r")
print("The slicing result for list : " + str(slc_list))
print("The slicing result for string : " + str(slc_str))


Python3
# Python3 code to demonstrate working of 
# Difference between Uni length slicing and Access Notation
# No Index out of bounds Exception in case of Slice operation
  
# initializing lists
test_list = [5, 7, 2, 6, 8, 1]
  
# printing string
print("The original list : " + str(test_list))
  
# access Notation results 
try :
    acc_list = test_list[17]
except Exception as e:
    acc_list = str(e)
      
# unilength slicing results 
slc_list = test_list[17 : 18]
  
# printing results 
print("The access notation result for list : " + str(acc_list))
print("The slicing result for list : " + str(slc_list))


输出
The original list : [5, 7, 2, 6, 8, 1]
The original string : 572681

The access notation result for list : 6
The access notation result for string : 6

The slicing result for list : [6]
The slicing result for string : 6

差异#2:在切片操作的情况下没有索引越界异常

在切片操作的情况下没有越界异常,但在访问表示法的情况下存在。

Python3

# Python3 code to demonstrate working of 
# Difference between Uni length slicing and Access Notation
# No Index out of bounds Exception in case of Slice operation
  
# initializing lists
test_list = [5, 7, 2, 6, 8, 1]
  
# printing string
print("The original list : " + str(test_list))
  
# access Notation results 
try :
    acc_list = test_list[17]
except Exception as e:
    acc_list = str(e)
      
# unilength slicing results 
slc_list = test_list[17 : 18]
  
# printing results 
print("The access notation result for list : " + str(acc_list))
print("The slicing result for list : " + str(slc_list))
输出
The original list : [5, 7, 2, 6, 8, 1]
The access notation result for list : list index out of range
The slicing result for list : []