循环输出冗余

时间:2018-08-09 21:21:52

标签: python string list for-loop

我正在尝试将一个长的typedef(C)分隔成单词,然后打印每行的第二个单词

variable = """int32_t  adc_cal_A;             / Simple point slope   calculation adjustment needed for the ADC */ \r\n
          int32_t  adc_cal_B;                 /* y = Ax + B */"""
list = variable.splitlines()

for line in list:
    wordlist =  line.split()

    for line in wordlist:
       output = wordlist[1][:-1]
       print output

它成功打印了我的测试列表中每行的第二个单词,但是它重复了该单词多次。结果是:

adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_A
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B
adc_cal_B

Process finished with exit code 0

任何人都知道为什么会这样。有简单的解决方案吗?

1 个答案:

答案 0 :(得分:0)

这是实现您所需要的一种简单方法:

variable = """int32_t  adc_cal_A;                 / Simple point slope   calculation adjustment needed for the ADC */ \r\n
          int32_t  adc_cal_B;                 /* y = Ax + B */"""

for num_line, line in enumerate(variable.splitlines()):
    try:
        print(f"line={num_line} token={line.split()[1]}")
    except Exception as e:
        # Probably line is empty?
        pass

输出:

line=0 token=adc_cal_A;
line=2 token=adc_cal_B;

如果您只想要第二个令牌而没有其他礼物,请使用print(line.split()[1]),即:

adc_cal_A;
adc_cal_B;