Python - 从带有整数和字符串的文本文件中查找最大值和最小值
我一直在尝试从文本文件中获取最大/最小值,但我不知道如何只获取文本的整数,python 总是获取文本中的字符串并给我一个错误。 这是文本文件的示例 在此处输入图片说明 谢谢你,
I've been trying to get the maximum/minimum value from a text file, but I don't know how to only take the integer of the text, python always take the string in the text and give me an error.
Here's an exemple of the text file
enter image description here
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
pandas.DataFrame.dtypes
查找文本的int
值。这是您的数据,我假设您将其保存为test.txt
文件:您可以使用
Pandas
读取数据,然后查找包含int 的列值。然后你可以搜索最大整数值:
然后如果你尝试
print(maximum)
,你会得到这个:所以关键部分是检查每列成员的类型如果您尝试
print(df.dtypes)
,您将得到:这意味着,第一列(其中包含 E1、E2、...、E8 ) 有一个
object
类型,并且其他的具有int64
类型(您正在寻找)。You can find
int
values of your text usingpandas.DataFrame.dtypes
. Here is your data and I assume that you saved it as atest.txt
file:You can read the data using
Pandas
and then find the columns that containint
values. Then you can search for the maximum integer value:Then if you try to
print(maximum)
, you'll get this:So the critical part is to check the type of members of each column of the DataFrame! If you try to
print(df.dtypes)
, you'll get this:This means, the first column(which contained E1, E2, ..., E8) has an
object
type, and the other ones have anint64
type(which you're looking for).除非需要,否则不要使用 Pandas。有一个更干净、更简单的解决方案:
它在
sum(,[])
部分效率有些低,但这只是为了简洁而使用。Don't use Pandas unless needed. There's a much cleaner, simpler solution:
It's somewhat inefficient in the
sum(,[])
part, but that's only been used for brevity.您还没有标记或提及任何库,因此我假设您需要普通 Python 中的解决方案。你的文件格式有点明确,你想找到哪个最小的整数?如果您想分别获取每行中的最小整数,您可以打开文件,将行读入列表并从中提取整数:
You haven't tagged or mentioned any libraries so I'm going to assume you want a solution in vanilla Python. Your file format is a bit unambiguous, which smallest integer do you want to find? If you want to get the smallest integer in each row separately, you can open the file, read the lines into a list and extract the integers out of it: