问题:如何在Python中将字符串转换为整数?

我有一个来自MySQL查询的元组,像这样:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

我想将所有字符串元素转换为整数,然后将它们放回列表列表中:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

我试图用它来实现它,eval但是还没有得到令人满意的结果。

I have a tuple of tuples from a MySQL query like this:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

I’d like to convert all the string elements into integers and put them back into a list of lists:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

I tried to achieve it with eval but didn’t get any decent result yet.


回答 0

int()是Python标准的内置函数,用于将字符串转换为整数值。您使用一个包含数字作为参数的字符串来调用它,它返回转换为整数的数字:

print (int("1") + 1)

上面的照片2

如果您知道列表T1的结构(它仅包含列表,仅一个级别),则可以在Python 2中执行此操作:

T2 = [map(int, x) for x in T1]

在Python 3中:

T2 = [list(map(int, x)) for x in T1]

int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

print (int("1") + 1)

The above prints 2.

If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 2:

T2 = [map(int, x) for x in T1]

In Python 3:

T2 = [list(map(int, x)) for x in T1]

回答 1

您可以通过列表理解来做到这一点:

T2 = [[int(column) for column in row] for row in T1]

内部列表理解([int(column) for column in row])建立一个listint期从序列int-able物体,如小数字符串中row。外部列表推导([... for row in T1]))生成一个内部列表推导的结果的列表,该结果适用于中的每个项目T1

如果任何行包含无法通过转换的对象,则代码段将失败int。如果要处理包含非十进制字符串的行,则需要一个更智能的函数。

如果您知道行的结构,则可以使用对行函数的调用来替换内部列表理解。例如。

T2 = [parse_a_row_of_T1(row) for row in T1]

You can do this with a list comprehension:

T2 = [[int(column) for column in row] for row in T1]

The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

The code snippet will fail if any of the rows contain objects that can’t be converted by int. You’ll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

T2 = [parse_a_row_of_T1(row) for row in T1]

回答 2

我宁愿只使用理解列表:

[[int(y) for y in x] for x in T1]

I would rather prefer using only comprehension lists:

[[int(y) for y in x] for x in T1]

回答 3

代替put int( ),put float( )可以让您将小数与整数一起使用。

Instead of putting int( ), put float( ) which will let you use decimals along with integers.


回答 4

到目前为止,我都同意所有人的回答,但是问题是,如果您没有所有整数,它们将崩溃。

如果要排除非整数,则

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())

这仅产生实际数字。我不使用直接列表推导的原因是因为列表推导会泄漏其内部变量。

I would agree with everyones answers so far but the problem is is that if you do not have all integers they will crash.

If you wanted to exclude non-integers then

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())

This yields only actual digits. The reason I don’t use direct list comprehensions is because list comprehension leaks their internal variables.


回答 5

T3=[]

for i in range(0,len(T1)):
    T3.append([])
    for j in range(0,len(T1[i])):
        b=int(T1[i][j])
        T3[i].append(b)

print T3
T3=[]

for i in range(0,len(T1)):
    T3.append([])
    for j in range(0,len(T1[i])):
        b=int(T1[i][j])
        T3[i].append(b)

print T3

回答 6

尝试这个。

x = "1"

x是一个字符串,因为它周围带有引号,但其中带有数字。

x = int(x)

由于x的数字为1,因此我可以将其变成整数。

要查看字符串是否为数字,可以执行此操作。

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

它应该打印到IDLE True,因为x是一个数字。

y_test = is_number(y)

print(y_test)

它应该打印为IDLE False,因为y中没有数字。

Try this.

x = "1"

x is a string because it has quotes around it, but it has a number in it.

x = int(x)

Since x has the number 1 in it, I can turn it in to a integer.

To see if a string is a number, you can do this.

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

It should print to IDLE True because x is a number.

y_test = is_number(y)

print(y_test)

It should print to IDLE False because y in not a number.


回答 7

使用列表推导:

t2 = [map(int, list(l)) for l in t1]

Using list comprehensions:

t2 = [map(int, list(l)) for l in t1]

回答 8

在Python 3.5.1中,这些工作如下:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

Enter number:  4.7
4
5

乔治。

In Python 3.5.1 things like these work:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

and

Enter number:  4.7
4
5

George.


回答 9

查看此功能

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

然后

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

您也可以检查

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

See this function

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

Then

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

You can also check

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

回答 10

适用于Python 2的另一个功能解决方案:

from functools import partial

map(partial(map, int), T1)

不过,Python 3会有些混乱:

list(map(list, map(partial(map, int), T1)))

我们可以用包装纸解决

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

Yet another functional solution for Python 2:

from functools import partial

map(partial(map, int), T1)

Python 3 will be a little bit messy though:

list(map(list, map(partial(map, int), T1)))

we can fix this with a wrapper

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

回答 11

如果只是元组的元组,类似 rows=[map(int, row) for row in rows]就可以解决。(在其中有一个列表推导和对map(f,lst)的调用,该调用等于[f in a lst]中的f(a)。)

如果由于某种原因在数据库中有类似的东西,Eval 不是您想要做的__import__("os").unlink("importantsystemfile")。始终验证您的输入(如果没有其他问题,如果输入错误,则会引发int()异常)。

If it’s only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There’s a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

Eval is not what you want to do, in case there’s something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).


回答 12

您可以执行以下操作:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

You can do something like this:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

回答 13

我想分享一个似乎此处未提及的可用选项:

rumpy.random.permutation(x)

将生成数组x的随机排列。不完全是您的要求,但这是解决类似问题的潜在方法。

I want to share an available option that doesn’t seem to be mentioned here yet:

rumpy.random.permutation(x)

Will generate a random permutation of array x. Not exactly what you asked for, but it is a potential solution to similar questions.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。