将字符串转换为int值python

2024-04-20 03:32:20 发布

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

我想在Python中把一个字符串转换成一个特定的int值,比如“red”我想是1,“blue”转换成2,等等。我目前使用的是if-else语句。我有一个字符串的数据集,其中包含要与数字关联的公共字符串。请帮忙。在

def discretize_class(x):
    if x == 'first':
        return int(1)
    elif x == 'second':
        return int(2)
    elif x == 'third':
        return int(3)
    elif x == 'crew':
        return int(4)

Tags: 数据字符串returnifdef数字bluered
3条回答

假设,通过数据集,你的意思是

  • 文本文件
  • 数据库表
  • 字符串列表

所以第一件重要的事,你需要知道,你如何读取数据。例如

  • 测试文件:您可以简单地读取文件并遍历file对象
  • 数据库表:根据您使用的库,它将提供一个API将所有数据读入字符串列表
  • 你已经拿到了

使用内置的enumerate枚举所有字符串

用字符串交换枚举

或者使用dict comprehension(如果您的python版本支持),或者通过内置的dict将元组列表转换为字典

with open("dataset") as fin:
    mapping = {value: num for num, value in enumerate(fin)}

这将提供一个dictionary,其中每个字符串,ex,red或{}都映射到一个唯一的数字

你的问题有点模糊,但这也许有帮助。在

common_strings = ["red","blue","darkorange"]
c = {}
a = 0
for item in common_strings:
    a += 1        
    c[item] = a
# now you have a dict with a common string each with it's own number.

你需要用字典。我认为最好是:

dictionary = {'red': 1, 'blue': 2}
print dictionary['red']

或者使用您刚刚添加的新代码:

^{pr2}$

相关问题 更多 >