博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 写文件
阅读量:4222 次
发布时间:2019-05-26

本文共 2101 字,大约阅读时间需要 7 分钟。

file_ex = open('data.txt', 'w')

如果文件已存在,完全清除现有内容。如果不存在,则创建。

追加到文件,使用 a。

读和写,不清除,用 w+

if 'file_ex' in locals():

   file_ex.close()

list相加:

>>> [1,2,3] +[4,5,6]

[1, 2, 3, 4, 5, 6]

合情合理,因为str也是list。连个str拼接也是 +。

>>> [1,2,3] +[4,5,6]

[1, 2, 3, 4, 5, 6]

但是:

>>> [1,2,3]+"qwer"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    [1,2,3]+"qwer"
TypeError: can only concatenate list (not "str") to list

上面报错。尽管两者都是list,但是列表和字符串无法拼接

但是:

>>>[1,2,3] +[4,'tr',6]+['gg']

[1, 2, 3, 4, 'tr', 6, 'gg']

这样就没有问题

extend修改原先,+ 创建新的。extend 效率高

>>> p='rw'

>>> 'w' in p
True
>>> 'x' in p
False
>>> 

>>> num=[100,34,678]

>>> len(num)
3
>>> max(num)
678
>>> min(num)
34
>>> 

>>> num=['22','gg','vb']

>>> ''.join(num)
'22ggvb'
>>> 

>>> num

['22', 'gg', 'vb']
>>> del num[2]
>>> num
['22', 'gg']

>>> ['to', 'be', 'to'].count('to')

2
>>> x=[[1,2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1
>>> 

index 找第一个

>>> ['to', 'be', 'to'].index('to')

0
>>> ['to', 'be', 'to'].index('be')
1
>>> 

>>> num = [1,2,3]

>>> num.insert(2, 'four')
>>> num
[1, 2, 'four', 3]
>>> 

pop默认是最后一个

>>> num  

[1, 2, 'four', 3]
>>> num.pop(2)
'four'
>>> num
[1, 2, 3]
>>> num.pop()
3
>>> num
[1, 2]
>>> 

remove第一个匹配项

>>> x

['to', 'be', 'to']
>>> x.remove('to')
>>> x
['be', 'to']
>>> remove没有返回值,但pop有

>>> x

['be', 'to']
>>> x.reverse()
>>> x
['to', 'be'] 无返回值

>>> reversed(x)

<list_reverseiterator object at 0x00000000037BCFD0>
>>> list(reversed(x))
['be', 'to']
>>> reversed不返回列表,返回迭代器iterator。要使用list转换成列表。

sort不返回值。sorted 返回。好像加ed 的都返回,不加的不返回。。

x.sort().reverse() 不行,因为sort返回值是None。

>>> x.sort().reverse()

Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    x.sort().reverse()
AttributeError: 'NoneType' object has no attribute 'reverse'
>>> 

sorted(x).reverse()可以

>>> sorted(x).reverse()

>>> x
['be', 'to']
>>> 

>>> x=['aardvasr','abaddg','asd','dd']

>>> x.sort(key=len)
>>> x
['dd', 'asd', 'abaddg', 'aardvasr']
>>> 

>>> x.sort(key=len, reverse=False)

>>> x
['dd', 'asd', 'abaddg', 'aardvasr']# 怎么没反过来呢???

>>> x.sort(key=len, reverse=True)

>>> x
['aardvasr', 'abaddg', 'asd', 'dd']#这样可以,默认值是False,很合理!

转载地址:http://dqmmi.baihongyu.com/

你可能感兴趣的文章
2006年了
查看>>
今天好消息不少。。
查看>>
偶尔也会感慨。。
查看>>
难得的轻闲-_-
查看>>
明天开始复习咯!
查看>>
第二天
查看>>
郁闷的问题
查看>>
阶段性胜利。。
查看>>
有点儿累了,最近特别能吃
查看>>
project的架构模式
查看>>
总结一下细节问题
查看>>
重新整合了一下代码
查看>>
有点儿伤感。。
查看>>
我要开始疯狂code了。。。
查看>>
在写我的论坛ing...
查看>>
页面间的信息传递
查看>>
进入了比较困难的阶段
查看>>
初见成效
查看>>
于根伟退役了。。
查看>>
大年初一的晚上
查看>>