简体   繁体   English

将字母列表转换为数字列表

[英]Turning a list of letters into a list of numbers

I need to turn a list of numbers into a list of letters. 我需要将数字列表转换为字母列表。

More specifically, I need to read PZ and turn it into PZx , such that the first distinct letter appearing in PZ assumes in PZx the number 1 , the second distinct letter assumes the number 2 , the third distinct letter assumes the number 3 , and the fourth distinct letter assumed the number 4 . 更具体地说,我需要阅读PZ并将其转换为PZx ,以便出现在PZ中的第一个不同的字母在PZx中假设数字1 ,第二个不同的字母假设数字2 ,第三个不同的字母假设数字3 ,并且第四个不同的字母采用数字4 Example: 例:

PZ = ['R','O','B','O','R','R','B','G','O','G','B','G']

PZx = [1,2,3,2,1,1,3,4,2,4,3,4]

I need to write a function that turns any given PZ into PZx according to this rule. 我需要编写一个函数,根据此规则将任何给定的PZ转换为PZx

You could use a dictionary and setdefault , from the documentation: 您可以从文档中使用字典和setdefault

If key is in the dictionary, return its value. 如果key在字典中,则返回其值。 If not, insert key with a value of default and return default. 如果不是,请插入具有默认值的密钥,然后返回默认值。 default defaults to None. 默认默认为无。

Code: 码:

PZ = ['R','O','B','O','R','R','B','G','O','G','B','G']
uniques = {}
PZx = [uniques.setdefault(l, len(uniques) + 1) for l in PZ]
print(PZx)

Output 产量

[1, 2, 3, 2, 1, 1, 3, 4, 2, 4, 3, 4]

I think you can use list index and have a simple loop like this 我认为您可以使用列表索引并有一个像这样的简单循环

occured = []
for item in PZ:
    if item not in occured:
        occured.append(item)
    PZx.append(occured.index(item) + 1)
In [1]: PZ = ['R','O','B','O','R','R','B','G','O','G','B','G']

In [2]: d = {}

In [3]: PZx = []

In [4]: n = 1
In [5]: for x in PZ:
...:     if x not in d:
...:         d[x] = n
...:         n += 1
...:     PZx += [d[x]]
...:

In [6]: PZx
Out[6]: [1, 2, 3, 2, 1, 1, 3, 4, 2, 4, 3, 4]

This could be done easily with a dictionary. 使用字典可以轻松做到这一点。 Try something like this. 尝试这样的事情。

PZ = ['R','O','B','O','R','R','B','G','O','G','B','G']
PZx = []
dict = {}
count = 1

for letter in PZ:
    if letter not in dict.keys():
        dict[letter] = count
        PZx.append(dict[letter])
        count+=1
    else:
        PZx.append(dict[letter])

now PZx should equal [1,2,3,2,1,1,3,4,2,4,3,4] 现在PZx应该等于[1,2,3,2,1,1,3,4,2,4,3,4]

Another way to do it by using pandas and list comprehension: 使用熊猫和列表理解的另一种方法:

import pandas as pd

PZ = ['R', 'O', 'B', 'O', 'R', 'R', 'B', 'G', 'O', 'G', 'B', 'G']
PZ_unique = pd.unique(PZ).tolist()  # ['R', 'O', 'B', 'G']
PZx = [PZ_unique.index(pz) + 1 for pz in PZ]  # [1, 2, 3, 2, 1, 1, 3, 4, 2, 4, 3, 4]

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

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