Python初学的问题记录1-2

版权声明:欢迎转载,但是请标明文章作者和出处。 https://blog.csdn.net/handsomehuo/article/details/89286203

问题一

新建一个空列表,赋值时出现错误提示:IndexError: list index out of range

问题原因:Python和C的语法不同,对空列表不能直接进行指定位置的赋值。

问题解决:使用append函数进行赋值

举例:编写一个函数返回最大值和最小值

def function2():
    list1 = []
    while True:
        a = int(input('请输入整数 按0结束'))
        if a == 0:
            break
        else:
            list1.append(a)
            #C的方式是以下,会出现报错,原因是空列表不能直接指定位置
            #n=0
            #list1[n] = a
            #n += 1

    print('max is %d' %max(list1))
    print('min is %d' %min(list1))

function2()

问题二

对list列表进行文件操作,open与write文件输入输出问题

写入文件使用的是write函数,如果直接把write后面加list列表,系统会提示write的参数必须是str:

TypeError: write() argument must be str, not list

采用强制转换的策略,看一下输出结果:

file3 = open('test_file.txt', 'w')
list3 = ['\n , this is a test list ']

file3.write(str(list3))
file3.close()

写到file3的文件内容是:

['\n , this is a test list ']

很显然,这不是我们想要的结果,因为转义字符\n被原样输出了,因此这样的方式其实是保留了列表原样的显示方式。

所以换一种显示方法,用for循环输出写入文件

file3 = open('test_file.txt', 'w')
list3 = ['\n , this is a test list ']

if len(list3) == 1:
    file3.write(list3[0])
else:
    for i in range(0, len(list3)-1):
        file3.write(list3[i])

file3.close()

写到file3的文件内容是:


 , this is a test list 

这是正常显示内容。

猜你喜欢

转载自blog.csdn.net/handsomehuo/article/details/89286203
1-2