我正在做一个编码问题,基本上,我正在将以下数据组织到一个列表中。
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
如何只读取每行的前三个字符,并将它们严格存储在列表中?例如,我只想要数字1和3,然后跳过该行的其余部分,转到下一行并执行相同的操作。由于它是整数和单词的混合,执行int(input())只会在编译器到达非整数部分时抛出错误,如"-“或":”
发布于 2020-12-28 05:54:06
一种方法是将输入作为字符串,然后进行字符串操作:
s = input("Enter the string")
res = []
t = s.split(" ")[0].split("-")
res.extend(list(map(int,t)))
如果想要添加多个输入,可以将逻辑移到while循环中,并继续n次:
In [5]: def extract_num(s,res=[]):
...: t = s.split(" ")[0].split("-")
...: res.extend(list(map(int,t)))
In [13]: def extract_numbers():
...: res = []
...: while True:
...: user_input = input("Enter the string ")
...: extract_num(user_input,res)
...: answer =input("Do you want to continue,yes or no")
...: if answer.lower() != "yes":
...: break
...: print(res)
...:
In [14]: extract_numbers()
Enter the string 1-3 a: abcde
Do you want to continue,yes or noYes
Enter the string 1-3 a: abcde
Do you want to continue,yes or nono
[1, 3, 1, 3]
这是基于所有输入都是相同格式的假设。
发布于 2020-12-28 05:57:49
数据存储在“data.txt”中:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
我将使用正则表达式,只是为了提取行首的整数:
import re
file = open('data.txt', 'r')
data = []
for line in file:
x = re.findall("^(\d+)-(\d+)", line)
data.append(x[0])
file.close
data
具有以下值:[('1', '3'), ('1', '3'), ('2', '9')]
https://stackoverflow.com/questions/65470723
复制相似问题