Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 排序()仅按第一位数字排序_Python - Fatal编程技术网

Python 排序()仅按第一位数字排序

Python 排序()仅按第一位数字排序,python,Python,我需要对表的第一列进行排序。看起来像 6000 799 7000 352 8000 345 9000 234 10000 45536 11000 3436 1000 342 2000 123 3000 1235 4000 234 5000 233 我希望第一列按升序排列,但它只按第一位数字排序,而不是按整列的值排序,即 1000 342 10000 45536 11000 3436 2000 123 但是我想要 1000 342 2000 123 3000 1235 etc 目前正在尝

我需要对表的第一列进行排序。看起来像

6000 799 
7000 352
8000 345
9000 234
10000 45536 
11000 3436
1000 342
2000 123
3000 1235
4000 234
5000 233
我希望第一列按升序排列,但它只按第一位数字排序,而不是按整列的值排序,即

1000 342
10000 45536
11000 3436
2000 123
但是我想要

1000 342
2000 123
3000 1235
etc
目前正在尝试:

SortInputfile=open("InterpBerg1","r")
line=SortInputfile.readlines()
line.sort()
map(SortOutputfile.write, line)

对于数字顺序,应将字符串转换为数字。要即时执行,请使用
参数:

outfile.writelines(sorted(
    open('InterpBerg1'),
    key = lambda l: int(l.split(maxsplit=1)[0])))
编辑:我同意其他人建议在处理文件时使用
语句,因此:

with open('Output', 'w') as outfile, open('InterpBerg1') as infile:
    outfile.writelines(sorted(infile,
        key = lambda l: int(l.split(maxsplit=1)[0])))

sort
sorted
函数支持一个键参数,该参数允许您指定用于执行排序的键。由于您需要数字排序顺序而不是字母排序顺序,因此需要提取第一列并将其转换为int:

SortInputfile=open("InterpBerg1","r")
line=SortInputfile.readlines()
line.sort(key=lambda line: int(line.split()[0]))
map(SortOutputfile.write, line)
更干净的版本可能是:

# read input file
with open(input_filename) as fh:
    lines = fh.readlines()

# sort lines
lines.sort(key=lambda line: int(line.split()[0]))

# write output file
with open(output_filename, 'w') as fh:
    fh.writelines(lines)

和其他答案一样——只是落后了几分钟,而且我的可读性更强一些

lines = []

with open("InterpBerg1","r") as f:
    for line in f:
        lines.append(tuple(int(i) for i in line.split()[:]))

print sorted(lines)

首先,您应该知道在Python中有两种标准的列表排序方法。第一个是
sorted()
,它是一个通用的内置函数,用于获取列表并返回列表的已排序副本;第二个是
.sort()
,它是一个内置的列表方法,用于对该列表进行排序(并返回
None
)。您正在使用
.sort()
;没有
.sorted()

第二,列表中的项目不是整数;它们是弦。您可以从使用
readlines()
创建列表这一事实看出这一点,该列表返回一个字符串数组。对字符串进行排序时,默认情况下它们按字母顺序排序。这就是为什么在您的示例中,它们似乎是按“仅第一个数字”排序的


为了按其他方式排序,您有两个选项,它们都表示为
sorted()
函数和
.sort()
方法的关键字参数。第一个是
参数,正如其他几个答案中已经提到的,粗略地说,它定义了您希望用于排序的列表项的质量或属性;在本例中,您希望使用第一个数字的值。您可以通过将字符串按空格分割、获取第一个标记并转换为int来实现这一点(Lev Levitsky和bikeshedder的答案都给出了相应的实现方法)。传递给
键的值必须是一个函数(标准函数或lambda函数),该函数将列表项作为输入并返回所需值。您可以使用的另一个参数是
cmp
参数,它是一个函数,将两个列表项(或它们的键,如果您还定义了
参数)作为输入,并返回一个值,指示哪个项“更大”。这是一个稍微复杂的功能,但是它为您的排序增加了一些灵活性。

感谢您的详细解释,我们对这两种方法感到非常困惑!