📜  Python - 列表中的索引值重复

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

Python - 列表中的索引值重复

给定一个元素列表,任务是编写一个Python程序,根据该索引中的值重复每个索引值。

方法 #1:使用列表理解+ enumerate()

在这里,我们使用 * 运算符执行重复任务,并且 enumerate() 用于获取索引和重复值。列表理解用于迭代所有元素。

Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# Using list comprehension + enumerate()
  
# initializing Matrix
test_list = [3, 0, 4, 2]
               
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate() gets index and value of similar index element
res = [ele for sub in ([idx] * ele for idx, 
                       ele in enumerate(test_list)) for ele in sub]
      
# printing result
print("Constructed List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# Using chain.from_iterable() + list comprehension
import itertools
  
# initializing Matrix
test_list = [3, 0, 4, 2]
               
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate() gets index and
# value of similar index element
# from_iterable() used to flatten
res = list(itertools.chain(*([idx] * ele for idx, 
                             ele in enumerate(test_list))))
      
# printing result
print("Constructed List : " + str(res))


输出:

The original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]

方法 #2:使用chain.from_iterable() +列表理解

在这里,我们使用 chain.from_iterable() 执行列表扁平化的最后一步。列表推导式执行所有元素的迭代任务。

蟒蛇3

# Python3 code to demonstrate working of
# Index Value repetition in List
# Using chain.from_iterable() + list comprehension
import itertools
  
# initializing Matrix
test_list = [3, 0, 4, 2]
               
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate() gets index and
# value of similar index element
# from_iterable() used to flatten
res = list(itertools.chain(*([idx] * ele for idx, 
                             ele in enumerate(test_list))))
      
# printing result
print("Constructed List : " + str(res))

输出:

The original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]