如何将字符串的字符放入特定的ord中

2024-09-30 20:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个职位列表,像这样:

a=[[1,0],[0, 2],[0, 4],[1,1],[0, 1],[0, 0],[1,3],[1,4],[1,2]]

我还有一个字符串,例如:

string = "HELLOWORL"

我想把字符串的每个字符按顺序排列 在矩阵(位置[0]是行,位置[1]是列)中的位置列表中,如下所示:

"string= WOELE
         HLLOR"

我该怎么做?你知道吗


Tags: 字符串列表string职位矩阵字符helloworlhllor
3条回答

您可以使用这些函数来实现:

^{}形成sa中元素的元组

^{}分隔第1行和第2行的字符

^{}对每行的字符进行排序

a = [[1, 0], [0, 2], [0, 4], [1, 1], [0, 1], [0, 0], [1, 3], [1, 4], [1, 2]]
s = "HELLOWORL"

first_line = sorted(filter(lambda i: i[0][0] == 0, zip(a, s)), key=lambda i: i[0][1])
second_line = sorted(filter(lambda i: i[0][0] == 1, zip(a, s)), key=lambda i: i[0][1])

word1 = ''.join(item[1] for item in first_line)
word2 = ''.join(item[1] for item in second_line)

输出:

>>> word1
'WOEL'
>>> word2
'HLLOR'

也可以这样做:

string = "HELLOWORL"

a = [[1,0],[0, 2],[0, 4],[1,1],[0, 1],[0, 0],[1,3],[1,4],[1,2]]

def value(v): return v[1]

import itertools
s = sorted(zip(string, a), key=value)
s = ((l, r) for (l, (r, c)) in s)
s = itertools.groupby(s, key=value)
print '\n'.join(''.join(c for (c, r) in g[1]) for g in s)

这个zip是带有列表的字符串,然后列表元素sorted将该列删除,并将项目groupby放入行中,每个组中的每个字母在删除行后join放入行中,然后将组join放入行中。你知道吗

打印内容:

WOEL
HLLOR

我不知道第二个E消失在哪里了。你知道吗

还有一个使用列表压缩和zip函数的选项。你知道吗

a=[[1,0],[0, 2],[0, 4],[1,1],[0, 1],[0, 0],[1,3],[1,4],[1,2]]
string = "HELLOWORL"
# zip(*a) extracts the first and the last element of each elemnt of a
# in a different list
rows, cols = zip(*a)
# Find the maximum possible value and sum 1in order to use then xrange
maxrow=max(rows) + 1
maxcol=max(cols) + 1
# Create an empty list with placeholders fot he characteres
b=[["" for _ in xrange(maxcol)] for _ in xrange(maxrow)]
for i in xrange(len(string)):
    letter=string[i]
    row,col = a[i]
    # Change the placeholder for the correct character
    b[row][col]=letter
# Paste everything pith join
result = "\n".join(["".join(i) for i in b])

which results in result=“沃尔\nHLLOR”

相关问题 更多 >