我正在试图弄清楚如何获取字符串中的字符顺序。当字母首次作为第一个订单出现时也应该考虑到例如:
getText()
有一种简单的方法吗?
答案 0 :(得分:3)
可能是这样的:
def ranker(s):
ranked = sorted(range(len(s)),key=lambda x: (s[x], x))
d = dict(zip(ranked, range(len(ranked))))
return [d[i]+1 for i in range(len(s))]
给了我
>>> ranker("abc")
[1, 2, 3]
>>> ranker("dfe")
[1, 3, 2]
>>> ranker("xef")
[3, 1, 2]
>>> ranker("aba")
[1, 3, 2]
>>> ranker("bba")
[2, 3, 1]
>>> ranker("bbac")
[2, 3, 1, 4]
答案 1 :(得分:0)
这是@ CoryKramer的答案的替代方案。它不使用元组上的index
方法,而是使用字典查找,对于长字符串可能更快。
def order(s):
ordered = sorted(s)
position = {c: i for i, c in enumerate(ordered)}
return [position[c]+1 for c in s]
>>> order('abc')
[1, 2, 3]
>>> order('dfe')
[1, 3, 2]
>>> order('xef')
[3, 1, 2]
答案 2 :(得分:0)
file = open("Class A.txt", "r")
f2 = file.read().split('|')
file.close()
print(f2)
答案 3 :(得分:0)
这是我的代码,试试吧
s = 'badca'
order = []
for x in range(len(s)):
order.append(0)
print(order)
for i in range(len(s)):
for j in range(len(s)):
if i == j:
order[i] = order[i] + 1
elif i != j:
if s[i] > s[j]:
order[i] = order[i] + 1
elif (s[i] == s[j]) and (j > i):
order[j] = order[j] + 1
print(order)