您需要编写三个函数来实现从包含逗号分隔数字的字符串创建列表的功能。
is_numeric()
:此函数具有一个字符串参数,如果字符串中的所有字符都是数字、逗号、空格或句点,则返回True
。如果有任何其他字符,则函数应返回False
。string_to_list()
:此函数接受一个字符串参数并返回字符串中数字的列表。首先,它应该调用is_numeric()
函数以检查字符串中是否有无效字符(例如字母)。如果有任何无效字符,它应该返回空列表。如果没有无效字符,它应该尝试从字符串中的数据构建列表。为此,它应该查看两个连续逗号之间的每个子字符串。如果该子字符串中没有句点,则应将子字符串转换为整数。如果只有一个句点(不多不少),则应将其转换为浮点数。如果两个连续逗号之间的任何子字符串都无法转换为整数或浮点数(例如“4.5.8”,因为它有太多句点),则函数仍应返回空列表。提示:split()
方法可能对这项任务有用。main()
:main()
函数将从用户那里获取一个字符串,然后调用string_to_list()
函数来从用户字符串构建一个列表,然后打印结果列表。接下来,它会询问用户是否要继续。如果他们想继续,他们应该输入 ‘y’。在这种情况下,函数 (main
) 应重复前面的步骤:向用户询问输入,将其转换为列表,再次询问用户是否要继续。依此类推,直到用户不想继续,在这种情况下,他或她应该输入 ‘n’。
- 解决方案
def is_numeric(s):
"""
Checks if a string contains only digits, commas, spaces, or periods.
Args:
s: The string to check.
Returns:
True if the string is numeric, False otherwise.
"""
numeric_characters = "0123456789., "
for char in s:
if char not in numeric_characters:
return False
return True
def string_to_list(s):
"""
Converts a string of comma-separated numbers to a list of numbers.
Args:
s: The string to convert.
Returns:
A list of numbers.
"""
if not is_numeric(s):
return []
# Split the string into a list of substrings, using commas as the delimiter.
substrings = s.split(",")
# Convert each substring to a number.
numbers = []
for substring in substrings:
if "." in substring:
numbers.append(float(substring))
else:
numbers.append(int(substring))
return numbers
def main():
"""
Gets a string from the user, converts it to a list of numbers, and prints the list.
Continues to do this until the user enters 'n' to quit.
"""
while True:
# Get a string from the user.
s = input("Enter a set of numbers (integers or floats) separated by comma:")
# Convert the string to a list of numbers.
numbers = string_to_list(s)
# Print the list.
print(numbers)
# Ask the user if they want to continue.
continue_ = input("Do you want to continue (y/n)? ")
# If the user enters 'n', quit the program.
if continue_ == "n":
break
if __name__ == "__main__":
main()
这个程序首先调用 is_numeric()
函数来检查用户输入的字符串是否包含任何无效字符。如果是,它打印错误消息并退出程序。如果不是,它调用 string_to_list()
函数将字符串转换为数字列表。然后,它打印列表并询问用户是否要继续。如果用户输入 ‘y’,程序将重复此过程。如果用户输入 ‘n’,程序将退出。