如何从文件中排序一个整数
How to sort an int from a file
我有这个代码:
import glob
import os
for file in glob.glob("./data/*.jpg"):
lel=(os.path.basename(file))
lel = (os.path.splitext(lel)[0])
list1 = lel
list1 = [int(x) for x in list1]
list1.sort()
print(list1)
它给出了这个输出:
[0]
[1]
[0, 1]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]
[2]
[0, 2]
[1, 2]
[2, 2]
[2, 3]
[2, 4]
[2, 5]
[2, 6]
[2, 7]
[2, 8]
[2, 9]
[3]
[0, 3]
[1, 3]
[2, 3]
[3, 3]
[3, 4]
[4]
[5]
[6]
[7]
[8]
[9]
有没有办法让它输出这个?:
0
1
2
3
4
5
6
7
8
9
10
etc etc..
此代码应该有效:
import glob
import os
list1 = []
for file in glob.glob("./data/*.jpg"): # iterate over filename
list1.append(
os.path.splitext(
os.path.basename(file)
)[0]
) # strip away path and extension and append to the list1
print(*sorted(list1)) # print it out
您正在遍历文件名的字母,并将每个字母转换为 int。
你甚至可以通过列表理解来做到这一点:
import glob
import os
list1 = [os.path.splitext(os.path.basename(filename))[0] for filename in glob.glob("./data/*.jpg")]
print(*sorted(list1))
据我所知,您有名为 0.jpg
的文件,最多 34.jpg
您需要删除 [int(x) for x in list1]
,因为这会得到一个列表 每个文件
如果您想按升序而不是字典顺序对数字进行排序,则在循环外创建一个列表,例如
import glob
import os
files = []
for file in glob.glob("./data/*.jpg"):
lel = os.path.basename(file)
lel = os.path.splitext(lel)[0]
files.append(int(lel))
files.sort()
for f in files:
print(f)
我有这个代码:
import glob
import os
for file in glob.glob("./data/*.jpg"):
lel=(os.path.basename(file))
lel = (os.path.splitext(lel)[0])
list1 = lel
list1 = [int(x) for x in list1]
list1.sort()
print(list1)
它给出了这个输出:
[0]
[1]
[0, 1]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]
[2]
[0, 2]
[1, 2]
[2, 2]
[2, 3]
[2, 4]
[2, 5]
[2, 6]
[2, 7]
[2, 8]
[2, 9]
[3]
[0, 3]
[1, 3]
[2, 3]
[3, 3]
[3, 4]
[4]
[5]
[6]
[7]
[8]
[9]
有没有办法让它输出这个?:
0
1
2
3
4
5
6
7
8
9
10
etc etc..
此代码应该有效:
import glob
import os
list1 = []
for file in glob.glob("./data/*.jpg"): # iterate over filename
list1.append(
os.path.splitext(
os.path.basename(file)
)[0]
) # strip away path and extension and append to the list1
print(*sorted(list1)) # print it out
您正在遍历文件名的字母,并将每个字母转换为 int。 你甚至可以通过列表理解来做到这一点:
import glob
import os
list1 = [os.path.splitext(os.path.basename(filename))[0] for filename in glob.glob("./data/*.jpg")]
print(*sorted(list1))
据我所知,您有名为 0.jpg
的文件,最多 34.jpg
您需要删除 [int(x) for x in list1]
,因为这会得到一个列表 每个文件
如果您想按升序而不是字典顺序对数字进行排序,则在循环外创建一个列表,例如
import glob
import os
files = []
for file in glob.glob("./data/*.jpg"):
lel = os.path.basename(file)
lel = os.path.splitext(lel)[0]
files.append(int(lel))
files.sort()
for f in files:
print(f)