簡體   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