繁体   English   中英

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

[英]Python For In Loop Matrix for User Input

因此,我已经在Overflow上搜索了几天,以解决我正在解决的问题。 我了解社区为遏制家庭作业问题所做的努力,但是我很沮丧,想学习这个概念并继续学习更多编程知识。

在Python中,我正在开发矩阵或2D数组。

这是用户对数组的编程要求,并将其与数组值进行比较:

然后要求用户在矩阵中输入一个用户的名字和姓氏,然后找到该人的相应信息(整行); 如果找不到,请打印“找不到用户!”

这是我到目前为止在该阵列上所拥有的。

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和编程的新手,并在书中看到了它们如何通过带有false和index的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范围循环的编码开始时不需要布尔标志或索引部分。 我只是展示了到目前为止的进展,并试图使该程序更好地工作。

我研究了For In Range的以下有用链接,但感到困惑。

对于数组中的In输入

阵列输入

测试数组中的用户输入

Python如果还有其他嵌套语句

我们还没有遍历类和对象,也没有看到如何做到这一点,也没有遍历numpy并尝试使用import numpy,并且由于我也是numpy的新手而遇到了一些问题。 我正在阅读《像Python的CS一样思考》,这是该课程的附加帮助,以及《以难的方式学习Python》。

谢谢你的时间。

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 

这将打印从0-9的数字,即i将具有值0 ,并由第三个参数1递增,直到其值为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]的大小, 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 s:

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

这种格式可能会给您一些有关如何实现您所要询问的想法

names_matrix的布局方式与其中的第一个列表不对应。 names_matrix的第一个列表是['lname', 'fname', 'city', 'state', 'zipcode'] ,这使人们认为其中的后续列表遵循该顺序。

其中, names_matrix中的后续列表是names_matrix列表,名字列表,城市列表,州列表和邮政编码列表。

我们可以使用zip()将其转换为跟随标题( names_matrix第一个列表zip()例如:

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

现在获取用户输入。 无需for循环即可获取用户输入:

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

您的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')

暂无
暂无

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

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