在Python中,我想将列表中的所有字符串转换为整数。
所以,如果我有:
results = ['1', '2', '3']
我该如何制作:
results = [1, 2, 3]
答案 0 :(得分:970)
使用map
函数(在Python 2.x中):
results = map(int, results)
在Python 3中,您需要将结果从map
转换为列表:
results = list(map(int, results))
答案 1 :(得分:319)
results = [int(i) for i in results]
e.g。
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
答案 2 :(得分:1)
比列表理解要扩展一点,但同样有用:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
例如
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
也:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
答案 3 :(得分:1)
有多种方法可以实现:
1)使用地图:
def toInt(string):
return int(string)
equation = ["10", "11", "12"]
equation = map(toInt, equation)
for i in equation:
print(type(i), i)
2)不使用map()进行操作
equation = ["10", "11", "12"]
new_list = []
for i in equation:
new_list.append(int(i))
equation = new_list
print(equation)
有很多方法可以做到这一点。
答案 4 :(得分:1)
这是一个简单的解决方案,其中包含查询解释。
#Python code SSH to windows machine and run curl
cmd = 'curl --retry 5 --retry-delay 5 -o filetoDownload.msi %s' % (download_url)
ssh.exec_command(cmd)
在这里, append()用于将项目(即程序中字符串(i)的整数版本)添加到列表(b)的末尾。
注意: int()是一个函数,可以帮助将字符串形式的整数转换回其整数形式。
输出控制台:
a=['1','2','3','4','5'] #The integer represented as a string in this list
b=[] #Fresh list
for i in a: #Declaring variable (i) as an item in the list (a).
b.append(int(i)) #Look below for explanation
print(b)
因此,仅当给定的字符串完全由数字组成,否则我们将可以将列表中的字符串项转换为整数,否则将产生错误。
答案 5 :(得分:0)
输入时,您只需一行即可完成
。[int(i) for i in input().split("")]
将其拆分到所需位置。
如果要转换列表而不是列表,只需将列表名称放在input().split("")
处即可。
答案 6 :(得分:0)
如果您的列表包含纯整数字符串,则可以使用公认的遮阳篷。如果您给它提供非整数的值,此解决方案将崩溃。
因此:如果您的数据可能包含整数,浮点数或其他内容,则可以利用自己的函数进行错误处理:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
输出:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
要在可迭代对象内部也处理可迭代对象,可以使用以下帮助程序:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
输出:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
答案 7 :(得分:0)
我还想添加Python | Converting all strings in list to integers
方法一:朴素方法
# Python3 code to demonstrate
# converting list of strings to int
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
方法#2:使用列表推导
# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(i) for i in test_list]
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
方法 #3:使用 map()
# Python3 code to demonstrate
# converting list of strings to int
# using map()
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using map() to
# perform conversion
test_list = list(map(int, test_list))
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
答案 8 :(得分:-1)
您可以使用 python 中的循环速记轻松将字符串列表项转换为 int 项
假设你有一个字符串 from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client
from tempfile import NamedTemporaryFile
import base64
import google.auth
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform',])
credentials.refresh(google.auth.transport.requests.Request())
cluster_manager = ClusterManagerClient(credentials=credentials)
cluster = cluster_manager.get_cluster(name=f"projects/{gcp_project_id}/locations/{cluster_zone_or_region}/clusters/{cluster_id}")
with NamedTemporaryFile(delete=False) as ca_cert:
ca_cert.write(base64.b64decode(cluster.master_auth.cluster_ca_certificate))
config = client.Configuration()
config.host = f'https://{cluster.endpoint}:443'
config.verify_ssl = True
config.api_key = {"authorization": "Bearer " + credentials.token}
config.username = credentials._service_account_email
config.ssl_ca_cert = ca_cert.name
client.Configuration.set_default(config)
# make calls with client
就去做,
result = ['1','2','3']
它会给你类似的输出
result = [int(item) for item in result]
print(result)