简体   繁体   English

将字符串转换为int值python

[英]Convert string to int value python

I want to convert a string to a specific int value in Python ie "red" I want to be 1, "blue" to 2, etc. I am currently using if-else statements. 我想在Python中将字符串转换为特定的int值,即“ red”,我想为1,“ blue”为2,以此类推。我目前正在使用if-else语句。 I have a dataset of strings with common strings that I want to associate with a number. 我有一个字符串数据集,其中包含要与数字关联的常见字符串。 Please help. 请帮忙。

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)

You need to use a dictionary. 您需要使用字典。 That would be best I think: 我认为那是最好的:

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

Or with the new code you added just now: 或使用您刚才添加的新代码:

def discretize_class(x):

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

print discretize_class('second')

Assuming, by datasets, you either mean a 假设通过数据集,您的意思是

  • text file 文本文件
  • database table 数据库表
  • a list of strings 字符串列表

So first thing importantly, you need to know, how you can read the data. 因此,首先重要的是,您需要知道如何读取数据。 Example for 例子

  • test file: You can simply read the file and iterate through the file object 测试文件:您可以简单地读取文件并遍历文件对象
  • database table: Based on what library you use, it would provide an API to read all the data into a list of string 数据库表:根据您使用的库,它将提供一个API以将所有数据读入字符串列表
  • list of strings: Well you already got it 字符串列表:嗯,您已经知道了

Enumerate all the strings using the built-in enumerate 枚举使用内置的所有字符串枚举

Swap the enumeration with the string 用字符串交换枚举

Either use dict-comprehension (if your python version supports), or convert the list of tuples to a dictionary via the built-in `dict 使用dict-comprehension(如果您的python版本支持),或者通过内置的dict将元组列表转换为字典

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

This will provide a dictionary , where each string, ex, red or blue is mapped to a unique number 这将提供一个dictionary ,其中每个字符串(例如, redredblue都映射到一个唯一的数字

Your question is a bit vague, but maybe this helps. 您的问题有点含糊,但这也许有帮助。

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.

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

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