通过python中的用户输入选择数组的坐标

时间:2016-03-19 19:33:07

标签: python-3.x

file_name = input("Enter the file name: ") #magicsquares.txt
#show users the table
infile = open(file_name, "r")
file = infile.readlines()
infile.close()
#converting the numbers in notepad into a list (integers)
table= []
for i in range (len(file)):
    row= file[i].split(' ')
for j in range (len(row)):
    row[j]= int(row[j])
table.append(row)
print (row)


#selecting cells
select1 = int(input("Enter row number: "))
select2= int(input("Enter column number: "))

这是一个魔术方块,其中列表位于记事本文本文件中。如何选择列表中的行和列,以便我可以更改列表中特定坐标的值?

例如,用户输入坐标[0] [1]。如何在记事本文件中找到该坐标并提示用户输入一个整数来替换坐标[0] [1]处的原始值?

1 个答案:

答案 0 :(得分:1)

我们假设您的输入文件sample.txt包含以空格' '分隔的数字列表,其中包含以下内容:

1 2 3 4
5 6 7 8
9 0 1 2
1 4 7 9

以上是类似矩阵的结构。

python代码看起来像这样:

import fileinput
import linecache

file_name = input("Enter the file name: ") #sample.txt

# selecting cells
select1 = int(input("Enter row number: ")) #0
select2 = int(input("Enter column number: ")) #1

# New value
newVal = int(input("Enter row number: ")) #100

# Get nth line from the input file and strip any newline chars
textToSearch = linecache.getline(file_name, select1+1).strip('\n')

# Transform to the line read to a list 
tmpList = [int(_) for _ in textToSearch.split(' ')]

# Replace the list with the new value and form the str line back again
tmpList[select2] =  newVal
textToReplace = ' '.join(str(_) for _ in tmpList)

# Modify the sample.txt file inplace 
with fileinput.FileInput(file_name, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(textToSearch, textToReplace), end='')

file.close()
linecache.clearcache()

sample.txt现在看起来像这样:

1 100 3 4
5 6 7 8
9 0 1 2
1 4 7 9

注意:这是Python3特有的

重要资源:

  1. linecache — Random access to text lines
  2. fileinput
  3. 其他值得一读的SO QAs:

    1. How to search and replace text in a file using Python?
    2. Go to a specific line in Python?