我有一个数字列表:
a=[6,8,1,0,5,0]
并且我需要以升序排序的顺序从原始列表中获取索引列表,除了这样的0个元素:
index=[3,4,1,0,2,0]
答案 0 :(得分:0)
a = [6, 8, 1, 0, 5, 0]
sorted_positions = {x: i for i, x in enumerate(sorted(a))}
# {0: 1, 1: 2, 5: 3, 6: 4, 8: 5}
indices = [sorted_positions[x] for x in a]
# [4, 5, 2, 1, 3, 1]
zeroes = a.count(0)
# 2
answer = [
0 if x == 0
else i - zeroes + 1
for i, x in zip(indices, a)
]
# [3, 4, 1, 0, 2, 0]
如果您不认识语法,则应搜索的术语:列表理解,字典理解和python三元运算符。
对于a=[3,3,1,1,2,2]
,给出[6, 6, 2, 2, 4, 4]
。
答案 1 :(得分:0)
使用numpy的argsort可以使此问题具有一定的美感
text = " I love python e "
out = ""
string_started = False
underscores_to_add = 0
for c in text:
if c == " ":
underscores_to_add += 1
else:
if string_started:
out += "_" * underscores_to_add
underscores_to_add = 0
string_started = True
out += c
print(out) # prints "I_love___python____e"