Python – 提取 List 中每个 Nth 元组的 Kth 元素
给定元组列表,提取每个第 N 个元组的第 K 个列元素。
Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3
Output : [3, 8, 10]
Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10.
Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 0, N = 3
Output : [4, 4, 1]
Explanation : From 0th, 3rd, and 6th tuple, 0th elements are 4, 4, 1.
方法#1:使用循环
在此,我们通过使用 range() 的第三个参数跳过 N 个值进行迭代,并使用循环将每个 Kth 值附加到列表中。
Python3
# Python3 code to demonstrate working of
# Extract Kth element of every Nth tuple in List
# Using loop
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8),
(6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# initializing N
N = 3
res = []
for idx in range(0, len(test_list), N):
# extract Kth element
res.append(test_list[idx][K])
# printing result
print("The extracted elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Kth element of every Nth tuple in List
# Using list comprehension
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8),
(6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# initializing N
N = 3
# Skipping N using 3rd param of range()
res = [test_list[idx][K] for idx in range(0, len(test_list), N)]
# printing result
print("The extracted elements : " + str(res))
输出
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements : [5, 7, 9]
方法#2:使用列表推导
在此,我们使用与上述相同的方法,使用列表理解使用单线执行提取元素的任务。
Python3
# Python3 code to demonstrate working of
# Extract Kth element of every Nth tuple in List
# Using list comprehension
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8),
(6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# initializing N
N = 3
# Skipping N using 3rd param of range()
res = [test_list[idx][K] for idx in range(0, len(test_list), N)]
# printing result
print("The extracted elements : " + str(res))
输出
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements : [5, 7, 9]