python - 使检查的字符串数量根据一行中的字符串数量而变化

标签 python python-3.x

标题实在是太糟糕了,不知道该怎么写。

本质上我需要检查 txt 文件的输入是否按字典顺序排列。我从文件中读取,将各个单词加载到列表中,然后使用 python 的“<”检查是否为真。

我需要帮助的部分是做

字1 <字2 <字3

无论列表中有多少个单词,无论文件中有多少行,都需要正确的次数。 所以如果第 1 行只有 2 个字长,它只会这样做

单词1 <单词2

但是第 1 行有 5 个单词长,它会检查

字1 <字2 <字3 <字4 <字5

我的代码现在到处都是,因为老实说我很困惑,我对 python 比较陌生,所以解释会有所帮助

with open ("lines.txt", "r") as myfile:
   linelist = myfile.readlines()
   count = len(linelist)
   l1 = linelist[0]
   line1split = l1.split()
   l1count = len(line1split)
   l2 = linelist[1]
   line2split = l2.split()
   l2count = len(line2split)
   l3 = linelist[2]
   line3split = l3.split()
   l3count = len(line3split)
   l4 = linelist[3]
   line4split = l4.split() 
   l4count = len(line4split) 
   l5 = linelist[4]
   line5split = l5.split()
   l5count = len(line5split) 
   line1split = l1.split()

     if line1split[0] < line1split[1]: 
       print('Line 1 is ascending.')

最佳答案

一种简单的方法是使用嵌套的 for 循环,第一个 for 循环迭代该行,第二个 for 循环迭代该行中的每个单词。示例-

with open ("lines.txt", "r") as myfile:
    for i, line in enumerate(myfile):
        flag = True
        words = line.split()
        for j, word in enumerate(words):
            if j == len(words) - 1:
                break
            elif word >= words[j+1]:
                flag = False
                break
        if flag:
            print('Line {} is ascending'.format(i+1))

关于python - 使检查的字符串数量根据一行中的字符串数量而变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823551/

相关文章:

python - 如何使用 python 2.7 获取发送和接收的总字节数?

python - 在 Python (PIL) 中确定 JPG 质量

python - PyTorch 中 "*"运算符在张量大小之前做什么?

python - python typing 模块中的 Set、FrozenSet、MutableSet 和 AbstractSet 之间有什么区别?

python请求ssl错误550

python - 在 Pandas 中重新编码分类变量

python - Python 中省略号的混淆

python - 如何使用正则表达式从文本中构建 python 列表?

python - 使用 C API 创建 Python 包

python - 在 Python 3 中迭代字典 items()、values()、keys()