我正在研究如何在Python中进行文件输入和输出.我编写了以下代码来读取文件中的名称列表(每行一个)到另一个文件,同时根据文件中的名称检查名称,并将文本附加到文件中的出现位置.代码有效.可以做得更好吗?
我想对with open(...输入和输出文件使用该语句,但无法看到它们在同一块中的含义,这意味着我需要将名称存储在临时位置.
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
outfile = open(newfile, 'w')
with open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
outfile.close()
return # …Run Code Online (Sandbox Code Playgroud) 这个问题的答案之一是
print len(s)>5 and 'y' or 'n'
print(len(s)>5 and 'y' or 'n') #python3
Run Code Online (Sandbox Code Playgroud)
如果长度s > 5,则'y'打印否则'n'是.请解释这是如何工作的原因.谢谢.
我知道这不是推荐的方法,但我想了解它的工作原理.
在按两个标准对 Python 列表进行排序中, Fouad 给出了以下答案:
sorted(list, key=lambda x: (x[0], -x[1]))
Run Code Online (Sandbox Code Playgroud)
我想将以下列表主要按元组列表排序,主要按每个元素中的第二项按升序排列,然后按降序排列第一个(字母)项:
[('Ayoz', 1, 18, 7), ('Aidan', 2, 4, 9), ('Alan', 2, 4, 9), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2), ('Tariq', 5, 4, 2)]
Run Code Online (Sandbox Code Playgroud)
给出答案:
[('Ayoz', 1, 18, 7), ('Alan', 2, 4, 9), ('Aidan', 2, 4, 9), ('Tariq', 5, 4, 2), ('Arlan', 5, 6, 7), ('Luke', 15, 16, 2)]
Run Code Online (Sandbox Code Playgroud)
如果可能,请使用上述方法。我试过
tlist = [('Ayoz', 1, 18, 7), ('Aidan', 2, 4, 9), ('Alan', 2, 4, 9), ('Arlan', 5, 6, 7), …Run Code Online (Sandbox Code Playgroud) 我是一个天生的业余编程新手,试图在Linux上使用Geany学习Python 3(3.2).我一直在尝试在Swaroop CH的Python 3教程中重写以下示例我的代码如下:
#!/usr/bin/env python3
# Filename: poem.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
with open('poem.txt', mode = 'w') as pfile:
pfile.write(poem)
with open('poem.txt', mode = 'r') as pfile:
while True:
line = pfile.readline()
if len(line) == 0:
break
print(line, end='')
Run Code Online (Sandbox Code Playgroud)
我无法编译程序.我收到以下错误,我不明白:
SyntaxError: ('invalid syntax', ('poem.py', 19, 24, " print(line, end='')\n"))
Run Code Online (Sandbox Code Playgroud)
运行代码时,我得到同样的错误.我删除后它工作正常end=' '.如果我省略它,则在诗的每一行之间都会打印一个空白行.
我很感激任何帮助/解释.
Python 3学习者:
这个问题有以下公认的答案:
rr,tt = zip(*[(i*10, i*12) for i in xrange(4)])
Run Code Online (Sandbox Code Playgroud)
返回两个元组.如果有人可以打破答案并解释它在Python 3中做了什么(我知道range()在Python 3中返回迭代器),我将不胜感激.我理解列表理解但是我对解压缩感到困惑(我认为你只能使用星号表达式作为赋值目标的一部分).
我同样对以下代码感到困惑.我理解结果和拉链(或者我认为),但是星号表达再次击败了我.
x2, y2 = zip(*zip(x, y))
Run Code Online (Sandbox Code Playgroud)
从这个:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
Run Code Online (Sandbox Code Playgroud)