简体   繁体   English

用户输入的Python For In In Loop矩阵

[英]Python For In Loop Matrix for User Input

So I have been searching on Overflow for a few days now for a problem that I am working on. 因此,我已经在Overflow上搜索了几天,以解决我正在解决的问题。 I understand the communities efforts to curb the homework questions, but I am stumped and would like to learn this concept and move on to learn more programming. 我了解社区为遏制家庭作业问题所做的努力,但是我很沮丧,想学习这个概念并继续学习更多编程知识。

In Python I am developing a Matrices or 2D Array. 在Python中,我正在开发矩阵或2D数组。

Here are the Array's Programming requirements from the user and comparing the value to the arrays value: 这是用户对数组的编程要求,并将其与数组值进行比较:

Then ask the user to enter both the first name and last name of one of the users in the matrix, then print the corresponding information (entire row) for that person if found; 然后要求用户在矩阵中输入一个用户的名字和姓氏,然后找到该人的相应信息(整行); if not found, print 'User Not Found!' 如果找不到,请打印“找不到用户!”

Here's what I have so far on that array. 这是我到目前为止在该阵列上所拥有的。

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

I'm new to python and programming and have seen in the book how they made this with a While Loop with the false and index. 我是python和编程的新手,并在书中看到了它们如何通过带有false和index的While循环实现此功能。 I was having difficulty understand pass by values and references I think as well. 我也很难理解我认为的价值观和参考。

# 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.'

I was wondering how to do this with a For In Range Loop. 我想知道如何使用范围内循环进行此操作。 It might be a Nested Loop and those are a bit more tricky. 这可能是一个嵌套循环,而且有些棘手。

I don't believe I need the boolean flag or index part at the beginning of my coding for a For In range loop. 我认为在For In范围循环的编码开始时不需要布尔标志或索引部分。 I was just showing my progress so far and was trying to get this program to work better. 我只是展示了到目前为止的进展,并试图使该程序更好地工作。

I researched the following helpful links for For In Range but was getting stumped. 我研究了For In Range的以下有用链接,但感到困惑。

For In input in an Array 对于数组中的In输入

Array For In 阵列输入

Testing User Input in Array 测试数组中的用户输入

Python If Else Nested Statements Python如果还有其他嵌套语句

We haven't gone over Class and Objects and did see how to do that, and we also haven't gone over numpy and tried using import numpy and was having some problems with that as I'm new to numpy as well. 我们还没有遍历类和对象,也没有看到如何做到这一点,也没有遍历numpy并尝试使用import numpy,并且由于我也是numpy的新手而遇到了一些问题。 I am reading Think Like a CS with Python as additional help with the class as well as Learn Python the Hard Way. 我正在阅读《像Python的CS一样思考》,这是该课程的附加帮助,以及《以难的方式学习Python》。

Thanks for your time. 谢谢你的时间。

The correct syntax for a for loop iteration is: for循环迭代的正确语法是:

for x in iterable_object:
    # do something with each x

In english, take each item in your iterable_object , call it x , and perform some code involving x. 用英语,将iterable_object每个项目取为x ,并执行一些涉及x的代码。

for range objects: 对于range对象:

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

This will print the numbers from 0-9 , ie i will have the value 0 and is incremented by the third argument 1 until it is of value 10 and will not reenter the loop which means the last printed value will be 9 . 这将打印从0-9的数字,即i将具有值0 ,并由第三个参数1递增,直到其值为10并且不会重新进入循环,这意味着最后打印的值将为9

Python allows for some shorthand calls for this: Python允许对此进行一些速记:

for i in range(10):
    print i

does the same thing. 做同样的事情。 When one argument is provided is it interpreted as the upper limit. 提供一个参数时,将其解释为上限。

ref: range() 参考: range()

In your case you have this data: 就您而言,您具有以下数据:

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'] ])

You probably want information by column correct and ignoring the headers? 您可能希望按列正确显示信息,而忽略标题吗?

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

This means you want to iterate across the size of your names_matrix[1] , the second object in your list. 这意味着您要遍历names_matrix[1]的大小, 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]

will give you: 会给你:

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

It looks like you are trying to perform a search for someone in your data. 您似乎正在尝试搜索数据中的某人。 I would say to perform the user input before the loop, and then compare as you have done with the slight change to the indexing performed above. 我想说的是在循环之前执行用户输入,然后像上面所做的那样对上面执行的索引稍作更改,然后进行比较。

One note here, I find your data to be arranged in a rather strange manner. 请注意,我发现您的数据以一种非常奇怪的方式排列。 I like it would make more sense to structure it as: 我希望将其结构化为:

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

Making the iterations rather simple to iterate through your entries: 使迭代相当容易地迭代您的条目:

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 being the awesomeness that it is, provides very quick and easy operations for such transformations: python真是太棒了,它为此类转换提供了非常快速简便的操作:

names_matrix = zip(*names_matrix[1:])

The zip function in this case tells python to take the matrix, excluding the first entry which are your headers. 在这种情况下, 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'] ])

upzip it by each entry, which are your categories 通过每个条目将其上拉,这是您的类别

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'] )

and pair across each of these lists by their indexes into tuple s: 并通过它们的索引将每个列表配对成tuple s:

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

Now you can iterate across the user and not have to deal with the more complex indexing that you would need with your current setup. 现在,您可以遍历整个用户,而不必处理当前设置所需要的更复杂的索引。

This can be done as a temporary step for ease of use if you would rather keep the original data in the format you have it in currently. 如果您希望将原始数据保留为当前使用的格式,则可以将其作为易于使用的临时步骤。

Of course you can still do it if you prefer not to alter the data. 当然,如果您不想更改数据,仍然可以执行此操作。

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!')

This format could perhaps give you some ideas for how to implement what you are asking 这种格式可能会给您一些有关如何实现您所要询问的想法

The way your names_matrix is laid out does not correspond with the first list in it. names_matrix的布局方式与其中的第一个列表不对应。 The first list in the names_matrix is ['lname', 'fname', 'city', 'state', 'zipcode'] which makes one think that the subsequent lists in it follow that order. names_matrix的第一个列表是['lname', 'fname', 'city', 'state', 'zipcode'] ,这使人们认为其中的后续列表遵循该顺序。

Where as the subsequent lists in names_matrix are list of last names followed by list of first names followed by a list of cities followed by a list of states followed by a list of zip codes. 其中, names_matrix中的后续列表是names_matrix列表,名字列表,城市列表,州列表和邮政编码列表。

We can transform it to follow the header (first list in names_matrix ) using zip() like: 我们可以使用zip()将其转换为跟随标题( names_matrix第一个列表zip()例如:

fixed_names = zip(*names_matrix[1:])

This gives value of fixed_names as: 这给出了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')]

Now get the user input. 现在获取用户输入。 No need of a for loop to get the user input: 无需for循环即可获取用户输入:

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

Now iterate through fixed_names and see if userFirstName and userLastName are in them. 现在遍历fixed_names并查看其中是否userFirstNameuserLastName If so output the entire row: 如果是这样,则输出整个行:

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!')

Demo: 演示:

>>> 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']

Your names_matrix is a list of lists - each item in ```names_matrix`` is a list. 您的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()`` is useful if you also need the index of the item: 如果您还需要该项目的索引,则可以使用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']

Try this for indices of each individual item in the sub-lists : 尝试此操作以获取子列表中每个项目的索引:

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

zip() is also pretty handy, it preforms an operation similar to transposition. zip()也很方便,它执行类似于转置的操作。 In the following, the asterisk before names_matrix unpacks the sub-lists . 在以下内容中, 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM