将字符串转换为整数值 Python

0 投票
3 回答
685 浏览
提问于 2025-04-27 21:58

我想在Python中把一个字符串转换成特定的整数值,比如“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)
暂无标签

3 个回答

0

你的问题有点模糊,不过也许这样能帮到你。

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.
0

假设你提到的数据集是指:

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

首先,你需要知道如何读取这些数据。以下是一些例子:

  • 文本文件:你可以直接读取文件,然后逐行处理文件内容。
  • 数据库表:根据你使用的库,它会提供一个接口,让你可以把所有数据读取到一个字符串列表中。
  • 字符串列表:这个你已经有了。

使用内置的 enumerate 函数来列举所有字符串。

将列举的结果和字符串进行交换。

可以使用字典推导(如果你的 Python 版本支持的话),或者通过内置的 `dict` 将元组列表转换成字典。

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

这样你就会得到一个 字典,其中每个字符串,比如 redblue,都会对应一个唯一的数字。

3

你需要使用一个字典。我觉得这样做最好:

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

或者用你刚刚添加的新代码:

def discretize_class(x):

    dictionary = {'first': 1, 'second': 2, 'third': 3, 'crew': 4}
    return dictionary[x]

print discretize_class('second')

撰写回答