在Python中,我如何解析数字字符串,如"545.2222"相应的浮点值,545.2222?或者将字符串解析为"31"整数,31?
我只是想知道如何将一个浮点数 解析str为a float,并且(单独)将一个int 解析str为一个int.
如何将空格分隔的整数输入转换为整数列表?
输入示例:
list1 = list(input("Enter the unfriendly numbers: "))
Run Code Online (Sandbox Code Playgroud)
转换示例:
['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud) 我有一个清单:
Student_Grades = ['56', '49', '63']
Run Code Online (Sandbox Code Playgroud)
我想将每个条目转换为整数,以便我可以计算平均值.
这是我的转换代码:
for i in Student_Grades:
Student_Grades = [int(i)]
Run Code Online (Sandbox Code Playgroud)
我一直在收到错误
invalid literal for int() with base 10: '56,'
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么办
以下是关于我如何获得Student_Grades Choose_File = str的完整代码(输入("请输入要读入的文件的确切名称(包括文件扩展名):"))
with open(Choose_File, "r") as datafile:
counter = 1
x = 1
Student_Grades = []
Read = datafile.readlines()
info = Read[counter]
Split_info = info.split()
n = len(Split_info)
while x < n:
Student_Grades.append(Split_info[x])
x = x + 2
Run Code Online (Sandbox Code Playgroud)
文本文件的格式为'MECN1234 56,MECN1357 49,MATH1111 63'
我有一个字符串格式的数字列表。我使用 将该列表转换为 numpy 数组np.asarray()。
如何将字符串元素转换为整数?
问题是它为每个找到的单个数字在新行上打印每个结果.它也忽略了我创建的列表.
我想要做的是将所有数字放在一个列表中.我使用了join()但它不起作用.
代码:
def readfile():
regex = re.compile('\d+')
for num in regex.findall(open('/path/to/file').read()):
lst = [num]
jn = ''.join(lst)
print(jn)
Run Code Online (Sandbox Code Playgroud)
输出:
122
34
764
Run Code Online (Sandbox Code Playgroud) Stack Overflow 上有很多关于这个一般主题的问答,但它们要么质量很差(通常是初学者的调试问题暗示的),要么以其他方式错过了目标(通常是不够通用)。至少有两种极其常见的方法会使幼稚的代码出错,初学者从关于循环的规范中获益更多,而不是从将问题作为拼写错误或关于打印所需内容的规范中获益。所以这是我尝试将所有相关信息放在同一个地方。
假设我有一些简单的代码,可以对一个值进行计算x并将其分配给y:
y = x + 1
# Or it could be in a function:
def calc_y(an_x):
return an_x + 1
Run Code Online (Sandbox Code Playgroud)
现在我想重复计算 的许多可能值x。我知道for如果我已经有要使用的值列表(或其他序列),我可以使用循环:
xs = [1, 3, 5]
for x in xs:
y = x + 1
Run Code Online (Sandbox Code Playgroud)
while或者,如果有其他逻辑来计算值序列,我可以使用循环x:
def next_collatz(value):
if value % 2 == 0:
return value // 2
else:
return 3 * value + 1
def collatz_from_19():
x = 19
while x != 1:
x …Run Code Online (Sandbox Code Playgroud) 如何在二维整数列表中转换二维字符串列表?例子:
>>> pin_configuration = [['1', ' 1', ' 3'], ['2', ' 3', ' 5'], ['3'], ['4', ' 5'], ['5', ' 1'], ['6', ' 6'], ['7']]
>>> to [[1,1,3], [2,3,5], [3], [4,5], [5,1], [6,6], [7]]
Run Code Online (Sandbox Code Playgroud) 我有一个列表,它结合了来自两个来源的输入,最终看起来像下面给出的这个“pde_fin”。我需要提取列表中元素的整数值以进行进一步处理。但是,第二组数字似乎给出了一个错误(“int() 以 10 为基数的无效文字:“'1118'”)。
pde_fin =['2174', '2053', '2080', '2160', '2065', "'1118'", "'1098'", "'2052'", "'2160'", "'2078'", "'2161'", "'2134'", "'2091'", "'2089'", "'2105'", "'2109'", "'2077'", "'2057'"]
for i in pde_fin:
print(int(i))
Run Code Online (Sandbox Code Playgroud)