Python 中的用户输入矩阵的 for 循环

0 投票
3 回答
4482 浏览
提问于 2025-04-18 04:55

我在StackOverflow上搜索了几天,想解决我正在处理的问题。我理解社区对作业问题的限制,但我真的卡住了,想学习这个概念,然后继续学习更多的编程知识。

在Python中,我正在开发一个矩阵或二维数组。

这是用户对数组的编程要求,以及如何将输入的值与数组中的值进行比较:

然后让用户输入矩阵中某个用户的名字和姓氏,如果找到,就打印出该用户的所有信息(整行数据);如果没找到,就打印“用户未找到!”

这是我目前在这个数组上的进展。

rows = 5
cols = 7
names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
                 ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',     
                  'Alfonso'], 
                 ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
                 ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',  
                  'Denver','Gastonia'], 
                 ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
                 ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])

print names_matrix

#Create a Boolean variable flag.
found = False

#Create a variable to use as a loop counter.
index = 0

#Get the strings to search for.

for in names_matrix:  #Having problems here with what goes here in For In Loop
    userFirstName = raw_input('What is the user first name?')
    userLastName =  raw_input('What is the user last name?')

    if userFirstName == names_matrix [1] and userLastName == names_matrix [0]:
        print('')
    #I want to print the Matrix value from the user input
    else
        print('User Not Found!')
# nested find columns
# https://stackoverflow.com/questions/7845165/how-to-take-input-in-an-array-python

我对Python和编程还很陌生,书中提到过如何用While循环和布尔值来实现这个。我觉得我在理解值传递和引用方面也有些困难。

# Get the string to search for.
searchValue = raw_input('Enter a name to search for in the list: ')
# Step through the list searching for the
# specified name.
while found == False and index < len(names):
    if names[index] == searchValue:
        found = True
    else:
        index = index + 1
# Display the search results.
if found:
    print 'That name was found in element ' + str(index + 1)
else:
    print 'That name was not found in the list.'

我在想如何用For In Range循环来实现这个。可能需要用到嵌套循环,但那有点复杂。

我觉得在For In Range循环的开头不需要布尔标志或索引部分。我只是展示一下我目前的进展,想让这个程序运行得更好。

我查阅了一些关于For In Range的有用链接,但还是遇到了困难。

在数组中使用For In输入

数组中的For In

在数组中测试用户输入

Python的嵌套if-else语句

我们还没有学习类和对象,也不知道怎么做;另外,我们也还没有学习numpy,我在尝试使用import numpy时遇到了一些问题,因为我对numpy也很陌生。我正在阅读《像计算机科学家一样思考Python》和《笨办法学Python》作为额外的学习资料。

谢谢你的时间。

3 个回答

0

你的 names_matrix 是一个列表的列表——在这个 ```names_matrix``` 中,每个项目都是一个列表。

for thing in names_matrix:
    print thing

## ['lname', 'fname', 'city', 'state', 'zipcode']
## ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith', 'Alfonso']
## ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph']
## ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road', 'Denver', 'Gastonia']
## ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC']
## ['28210', '28337', '28974', '27457', '36827', '28037', '28559']

如果你还需要知道每个项目的索引位置,使用 ```enumerate()``` 会很有用:

for idx, thing in enumerate(names_matrix):
    print ' ', idx, ':', thing

##  0 : ['lname', 'fname', 'city', 'state', 'zipcode']
##  1 : ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith', 'Alfonso']
##  2 : ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph']
##  3 : ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road', 'Denver', 'Gastonia']
##  4 : ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC']
##  5 : ['28210', '28337', '28974', '27457', '36827', '28037', '28559']

你可以试试这个方法来获取每个子列表中每个项目的索引:

for idx, thing in enumerate(names_matrix):
    for ndx, item in enumerate(thing):
        print ' ', idx, ':', ndx, ':', item

zip() 也很方便,它的作用类似于转置。在下面的例子中,names_matrix 前面的星号表示将子列表“拆开”。

for idx, thing in enumerate(zip(*names_matrix)):
    print ' ', idx, ':', thing[1:]

##  0 : ('Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210')
##  1 : ('Johnson', 'Malcom', 'Monroe', 'NC', '28337')
##  2 : ('Terrell', 'Monkey', 'Broken Pine', 'SC', '28974')
##  3 : ('Wilson', 'Wilson', 'Hogwart', 'VA', '27457')
##  4 : ('Key', 'LeDoor', 'Spot in Road', 'AL', '36827')
2

一个for循环的正确写法是:

for x in iterable_object:
    # do something with each x

简单来说,就是从你的iterable_object(可迭代对象)中取出每一个项目,叫它x,然后对x做一些操作。

对于range对象:

for i in range(0,10,1):
    print i 

这段代码会打印出从09的数字,也就是说i的初始值是0,然后每次加上第三个参数1,直到i变成10,这时就不会再进入循环了,所以最后打印的值是9

Python还提供了一些简写方式来实现这个:

for i in range(10):
    print i

这样写也能达到同样的效果。当只提供一个参数时,它会被理解为上限。

参考:range()

在你的情况下,你有这些数据:

names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
             ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',     
              'Alfonso'], 
             ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
             ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',  
              'Denver','Gastonia'], 
             ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
             ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])

你可能想按列获取信息,对吧?并且忽略表头?

iteration 1 - Zdolfalos, Fred, Charlotte, NC, 28210
iteration 2 - Johnson, Malcom, Monroe, NC, 28337
etc ...

这意味着你想遍历names_matrix[1]的大小,也就是你列表中的第二个对象。

L = len(names_matrix[1])
print names_matrix[0][0],names_matrix[0][2],names_matrix[0][2],names_matrix[0][3],names_matrix[0][4]
for i in range(L):
    print names_matrix[1][i],names_matrix[2][i],names_matrix[3][i],names_matrix[4][i],names_matrix[5][i]

这样会给你:

lname fname city state zipcode
Zdolfalos Fred Charlotte NC 28210
Johnson Malcom Monroe NC 28337
Terrell Monkey Broken Pine SC 28974
Wilson Wilson Hogwart VA 27457
Key LeDoor Spot in Road AL 36827
Smith Jim Bob Denver NC 28037
Alfonso Ralph Gastonia NC 28559

看起来你是想在数据中搜索某个人。我建议你在循环之前先获取用户输入,然后像你之前做的那样进行比较,只需稍微调整一下索引。

这里有一点要注意,我觉得你的数据排列得有点奇怪。我觉得如果把它结构化成:

names_matrix = (
   [['lname',     'fname',   'city', 'state', 'zipcode'],               
    ['Zdolfalos', 'Fred',    'Charlotte','NC','28210'],
    ['Malcom',    'Johnson', 'Monroe', 'NC', '28337',],
    ['Monkey',    'Terrell', 'Broken Pine', 'SC','28974',],
    # ...etc...
   ] 

这样会让遍历你的条目变得简单:

for user in names_matrix[1:]: # [1:] means take the list from the 1st element to the end, noted by the lack of a number after the colon (on a 0 based index)
    print user

Python真是太棒了,它提供了非常快速和简单的操作来进行这样的转换:

names_matrix = zip(*names_matrix[1:])

在这种情况下,zip函数告诉Python从矩阵中取出数据,排除第一个条目,也就是你的表头。

([['lname', 'fname', 'city', 'state', 'zipcode'],
             ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',     
              'Alfonso'], 
             ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
             ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',  
              'Denver','Gastonia'], 
             ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
             ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])

然后按每个条目进行解压,这些条目就是你的类别。

zip(  ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith','Alfonso'],
      ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
      ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road','Denver','Gastonia'], 
      ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
      ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] )

并且根据它们的索引将这些列表配对成tuple(元组):

[ ('Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210'),
  ('Johnson', 'Malcom', 'Monroe', 'NC', '28337'),
  ('Terrell', 'Monkey', 'Broken Pine', 'SC', '28974'),
# ... etc ...
]

现在你可以遍历用户,而不必处理当前设置中更复杂的索引。

如果你更愿意保持原始数据的格式,这可以作为一个临时步骤来简化使用。

当然,如果你不想改变数据,还是可以这样做。

userFirstName = raw_input('What is the user first name?')
userLastName =  raw_input('What is the user last name?')
L = len(names_matrix[1])
for i in range(L):
    if userFirstName == names_matrix[0][i] and userLastName == names_matrix[1][i]:
        print('Found!')
    else
        print('User Not Found!')

这种格式可能会给你一些关于如何实现你所询问内容的灵感。

1

你的 names_matrix 的结构和里面的第一个列表不太一致。这个第一个列表是 ['lname', 'fname', 'city', 'state', 'zipcode'],这让人以为后面的列表也会按照这个顺序排列。

实际上,names_matrix 里面的后续列表是先列出姓,再列出名,然后是城市,接着是州,最后是邮政编码。

我们可以用 zip() 函数把它转换成和第一个列表(names_matrix 中的第一个列表)一致的格式,像这样:

fixed_names = zip(*names_matrix[1:])

这样就能得到 fixed_names 的值:

[('Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210'), ('Johnson', 'Malcom', 'Monroe', 'NC', '28337'), ('Terrell', 'Monkey', 'Broken Pine', 'SC', '28974'), ('Wilson', 'Wilson', 'Hogwart', 'VA', '27457'), ('Key', 'LeDoor', 'Spot in Road', 'AL', '36827'), ('Smith', 'Jim Bob', 'Denver', 'NC', '28037'), ('Alfonso', 'Ralph', 'Gastonia', 'NC', '28559')]

接下来获取用户输入。这里不需要用循环来获取用户输入:

userFirstName = raw_input('What is the user first name?')
userLastName =  raw_input('What is the user last name?')

然后遍历 fixed_names,看看 userFirstNameuserLastName 是否在里面。如果在,就输出整行数据:

found = False
for row in fixed_names:
    if userLastName in row and userFirstName in row:
        found = True
        print(list(row))
        break
if not found:
    print('User Not Found!')

演示:

>>> names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
...              ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',
...               'Alfonso'],
...              ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
...              ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',
...               'Denver','Gastonia'],
...              ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
...              ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])
>>> fixed_names = zip(*names_matrix[1:])
[('Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210'), ('Johnson', 'Malcom', 'Monroe', 'NC', '28337'), ('Terrell', 'Monkey', 'Broken Pine', 'SC', '28974'), ('Wilson', 'Wilson', 'Hogwart', 'VA', '27457'), ('Key', 'LeDoor', 'Spot in Road', 'AL', '36827'), ('Smith', 'Jim Bob', 'Denver', 'NC', '28037'), ('Alfonso', 'Ralph', 'Gastonia', 'NC', '28559')]
>>> userFirstName = 'Fred'
>>> userLastName = 'Zdolfalos'
>>> for row in fixed_names:
...     if userLastName in row and userFirstName in row:
...         print(list(row))
...     else:
...         print('User Not Found!')
...
['Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210']

撰写回答