基本上我要做的是将每行中的每个字符读入一个列表,然后在每行之后将该列表添加到另一个列表中(输入文件中每行一个列表,每个列表包含所有单个字符)每一行)
这是我到目前为止所做的,但它似乎没有起作用,我无法弄清楚原因。
allseq = []
with open("input.txt", "r") as ins:
seq = []
for line in ins:
for ch in line:
if ins != "\n":
seq.append(ch)
else:
allseq.append(seq)
seq[:] = []
print(allseq)
答案 0 :(得分:2)
Python中的字符串可以轻松转换为文字字符列表!让我们来做一个功能。
public List<LootItem> LootTable { get; set; }
这会打开一个文件进行阅读,读取所有行,剥去无关的空格,将一个字符列表放入列表中,然后返回最后一个列表。
答案 1 :(得分:1)
即使有更简单的方法(@Pierce回答),原始代码也存在两个问题。第二个是很重要的理解。
// inside my class
public void playRound() {
java.util.Iterator<Player> itr = layers.iterator();;
while(itr.hasNext()){
Player player =itr.next();
player.play(par);
}
// Supply this code!
}
测试文件:
allseq = []
with open("input.txt", "r") as ins:
seq = []
for line in ins:
for ch in line:
if ch != "\n": # Use ch instead of ins here.
seq.append(ch)
else:
allseq.append(seq)
seq = [] # Don't clear the existing list, start a new one.
print(allseq)
输出:
this is
some input
为了说明为什么需要第二个修复,当您将一个对象附加到列表时,对象的引用将放在列表中。因此,如果您稍后改变该对象,则列表的显示内容会发生变化,因为它引用了同一个对象。 [['t', 'h', 'i', 's', ' ', 'i', 's'], ['s', 'o', 'm', 'e', ' ', 'i', 'n', 'p', 'u', 't']]
将原始列表变为空。
seq[:] = []
您可以看到allseq包含与>>> allseq = []
>>> seq = [1,2,3]
>>> allseq.append(seq)
>>> allseq # allseq contains seq
[[1, 2, 3]]
>>> seq[:] = [] # seq is mutated to be empty
>>> allseq # since allseq has a reference to seq, it changes too.
[[]]
>>> seq.append(1) # change seq again
>>> allseq # allseq's reference to seq displays the same thing.
[[1]]
>>> allseq.append(seq) # Add another reference to the same list
>>> allseq
[[1], [1]]
>>> seq[:]=[] # Clearing the list shows both references cleared.
>>> allseq
[[], []]
的seq相同的引用:
id()
>>> id(seq)
46805256
>>> id(allseq[0])
46805256
>>> id(allseq[1])
46805256
使用不同的ID创建新列表,而不是改变相同的列表。
答案 2 :(得分:0)
如果您或其他任何人喜欢单行班轮,那么(基于Pierce Darragh的优秀答案):
allseq = [list(line.strip()) for line in open("input.txt").readlines()]