# Python |包含所有替代元素的列表用法详解

2021年3月16日11:58:31 发表评论 359 次浏览

``````# Python code to demonstrate
# to construct alternate element list
# using list comprehension

# initializing list
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]

# printing original list
print ( "The original list : " + str (test_list))

# using list comprehension
# to construct alternate element list
res = [test_list[i] for i in range ( len (test_list)) if i % 2 ! = 0 ]

# printing result
print ( "The alternate element list is : " + str (res))``````

``````The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]``````

``````# Python code to demonstrate
# to construct alternate element list
# using enumerate()

# initializing list
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]

# printing original list
print ( "The original list : " + str (test_list))

# using enumerate()
# to construct alternate element list
res = [i for j, i in enumerate (test_list) if j % 2 ! = 0 ]

# printing result
print ( "The alternate element list is : " + str (res))``````

``````The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]``````

``````# Python code to demonstrate
# to construct alternate element list
# using Slice notation

# initializing list
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]

# printing original list
print ( "The original list : " + str (test_list))

# using Slice notation
# to construct alternate element list
res = test_list[ 1 :: 2 ]

# printing result
print ( "The alternate element list is : " + str (res))``````

``````The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]``````