简体   繁体   English

将2d整数数组转换为字符串python

[英]convert a 2d array of integers into string python

convert a 2d array of integers into String. 将2d整数数组转换为String。 For example myArray = [[1,2,3],[3,4,5]] into myArrayL = [[a,b,c],[c,d,e]] and retain the shape of the 2d array 例如,将myArray = [[1,2,3],[3,4,5]]转换为myArrayL = [[a,b,c],[c,d,e]]并保留2d数组的形状

where 1 = "a" , 2 = "b", 3 = "c" 其中1 =“ a”,2 =“ b”,3 =“ c”

There are two parts to this. 这有两个部分。

First, how do you convert a number like 1 to a letter like 'a' , according to your rule? 首先,如何根据您的规则将数字(如1转换为字母(如'a' Second, how do you apply a function to all elements of a list? 其次,如何将函数应用于列表的所有元素?


For the first, one way to write it is with the chr function. 首先,一种写方法是使用chr函数。 This function takes an number and gives you the single-character string for the character with that code point. 此函数接受一个数字,并为您提供具有该代码点的字符的单字符字符串。 In particular, chr(65) is 'a' , chr(66) is 'b' , etc. So, we could just do chr(n + 64) . 特别是, chr(65)'a'chr(66)'b' ,等等。因此,我们可以做chr(n + 64)

Or we could use the ord function, which is the inverse of chr , so instead of hardcoding 64 and having to remember that's 1 less than 'a' , we can write 1 less than 'a' directly: 或者,我们可以使用ord函数,它是chr的反函数,因此不必对64进行硬编码,而必须记住它比'a'小1,我们可以直接写成比'a'小1:

def letter(n):
    return chr(n + ord('a') - 1)

Of course this isn't the only way to do it. 当然,这不是唯一的方法。 You could also, eg, use string.ascii_lowercase[n-1] . 您也可以使用例如string.ascii_lowercase[n-1]

(Note that either of these solutions not only works in Python 3, where the "code points" are always Unicode, but also in Python 2, where the "code points" are values in some unspecific 8-bit encoding, as long as the intended encoding has all of the lowercase letters in contiguous order, which is true for almost anything you're likely to ever encounter unless you've got some old EBCDIC files lying around.) (请注意,这些解决方案中的任何一种不仅在Python 3(其“代码点”始终为Unicode)中都有效,而且在Python 2中(其中“代码点”为某些非特定的8位编码中的值)都可以使用,只要预期的编码具有所有连续的小写字母,这几乎适用于几乎所有可能遇到的情况,除非您周围有一些旧的EBCDIC文件。)


For the second, you can use a list comprehension . 对于第二个,您可以使用列表推导 Your examples are flat (1D) lists, so we'd use a flat list comprehension: 您的示例是平面(1D)列表,因此我们将使用平面列表理解:

numbers = [2, 3, 4]
letters = [letter(n) for n in numbers]

If you have 2D lists of lists, just use a nested list comprehension : 如果您具有2D列表列表,则只需使用嵌套列表推导

numbers = [[2, 3], [4, 5]]
letters = [[letter(n) for n in row] for row in numbers]

You can corresponding Alphabets by indexing string.ascii_lowercase which returns all lower case alphabets. 您可以通过索引string.ascii_lowercase来返回所有小写字母的字母来对应字母。

import string 
myArray = [[1,2,3],[3,4,5]]
result_array = [[string.ascii_lowercase[element-1] for element in row] for row in myArray]

Result array: 结果数组:

[['a', 'b', 'c'], ['c', 'd', 'e']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM