comparing a list to a tuple, python 3.x - having problems getting the correct position to print

kensai01

I'm a new programmer and I'm having a difficult time finishing up my 4th program. The premise was to create a program that would take input from the user, creating a list then compares this list to a tuple. After it prints a statement letting the user know which items they chose correspond to the items in the tuple and also in which position they are in the tuple.

The problem I'm having is the last part, I can't get the correct position to print right and I fail to understand why. For example, if someone chose GPS correctly during their guesses, it should print position 0, but it doesn't. If water is chosen, it says it's in position 13...but it should be 5.

#here is the code I have so far:

number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user

survival_gear = () #this is the tuple that will be compared against
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")


#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in case of a survival situation, think Bear Grylls. Once chosen, your list will be compared to the top 10 survival items list.")
while number_items_input < 10:
    print("Please choose.")
    guessed_items = input()
    guessed_inventory_list.append(guessed_items)
    number_items_input = number_items_input + 1

print ("You have chosen the following:", guessed_inventory_list)


#block of code below here compares the input to the tuple    
t = 1
while t < 1:
    t = t + 1


for individual_items in guessed_inventory_list:

    for top_items in survival_gear:
        if individual_items == top_items:
            #finally the print statements below advise the user if they guessed an item and which position it's in.
            print ("You have chosen wisely", top_items)
            print ("It's in position", t, "on the survival list")
    t = t + 1
Ram

The reason you are getting a wrong index is because of the wrong nesting of loops , your outer loop should be the tuple you wish to compare and the inner loop should be the list generated from the input where as in this case it is reverse, see the below corrected code snippet
Code snippet:

for top_items in survival_gear:
    for individual_items in guessed_inventory_list:
        if individual_items == top_items:
            #finally the print statements below advise the user if they guessed an item and  which position it's in.
            print ("You have chosen wisely", top_items)
            print ("It's in position", t, "on the survival list")
    t = t + 1

The above code snippet should solve your problem , but your code contains

  • while loop which can be avoided using the range built in function

  • Incrementing the variable t manually can be avoided by using enumerate built in function

  • The nested forloop and if loop can be replaced by using the "in" membership test operator

Find the below updated code:

#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user

survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")

#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")

# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
    guessed_items = raw_input("Please choose:")
    guessed_inventory_list.append(guessed_items)

print ("You have chosen the following:", guessed_inventory_list)

# Enumerate is one of the built-in Python functions. 
# It returns an enumerate object. 
# In this case that object is a list of tuples (immutable lists), 
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be 
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
    #the "in" is a membership test operator which will test whether
    #individual_items is in list guessed_inventory_list
    if individual_items in guessed_inventory_list:
       #finally the print statements below advise the user if they guessed an item and which position it's in.
       print("You have chosen wisely", individual_items)
       print("It's in position", t, "on the survival list")

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Getting the first and second element from a 3 tuple in a list - Haskell

분류에서Dev

Sort list of tuples by specific tuple element in Python 3

분류에서Dev

Tuple, List Python 작업

분류에서Dev

Multiple %s with list/tuple in Python

분류에서Dev

Comparing a string with a list of strings to find anagrams in Python

분류에서Dev

python list not getting appended

분류에서Dev

Dealing with list.index(x) error in Python 3

분류에서Dev

Having quotation marks as a character in a python list

분류에서Dev

Having problems with batch if statements

분류에서Dev

여러 배열을 List <Tuple <x, x, x, x, >>로 표현

분류에서Dev

Problems removing dictionaries from list in Python

분류에서Dev

Problems getting jobs and education on Linkedin with Django (Python Social Auth)

분류에서Dev

Print float (x,y) data in a graph with Python

분류에서Dev

regex (vim) for print ... to print (...) for python2 to python3

분류에서Dev

We are having Merge Problems using Visual Studio 2013 Update 3 and Team Foundation 2013 RTM

분류에서Dev

Having problems with my bash script

분류에서Dev

I am having Problems with Arrays

분류에서Dev

Having problems understand the MySQL IF() and ELSE()

분류에서Dev

Comparing a list with haskell

분류에서Dev

Python 3 execution order quirk with print?

분류에서Dev

Python 3에서 list.index (x) 오류 처리

분류에서Dev

Having trouble getting calls to addChild() on nested children in vanilla ActionScript 3 to do anything

분류에서Dev

Python 3 print ([1, 2] 및 3) 출력 3

분류에서Dev

Getting correct perf version

분류에서Dev

String of list or strings to a tuple

분류에서Dev

Python Convert set to list, keep getting TypeError: 'list' object is not callable

분류에서Dev

ValueError: list.remove(x): x not in list python

분류에서Dev

The effect of position in comparing an object with a null reference

분류에서Dev

Comparing two files to print a line that matches a word

Related 관련 기사

  1. 1

    Getting the first and second element from a 3 tuple in a list - Haskell

  2. 2

    Sort list of tuples by specific tuple element in Python 3

  3. 3

    Tuple, List Python 작업

  4. 4

    Multiple %s with list/tuple in Python

  5. 5

    Comparing a string with a list of strings to find anagrams in Python

  6. 6

    python list not getting appended

  7. 7

    Dealing with list.index(x) error in Python 3

  8. 8

    Having quotation marks as a character in a python list

  9. 9

    Having problems with batch if statements

  10. 10

    여러 배열을 List <Tuple <x, x, x, x, >>로 표현

  11. 11

    Problems removing dictionaries from list in Python

  12. 12

    Problems getting jobs and education on Linkedin with Django (Python Social Auth)

  13. 13

    Print float (x,y) data in a graph with Python

  14. 14

    regex (vim) for print ... to print (...) for python2 to python3

  15. 15

    We are having Merge Problems using Visual Studio 2013 Update 3 and Team Foundation 2013 RTM

  16. 16

    Having problems with my bash script

  17. 17

    I am having Problems with Arrays

  18. 18

    Having problems understand the MySQL IF() and ELSE()

  19. 19

    Comparing a list with haskell

  20. 20

    Python 3 execution order quirk with print?

  21. 21

    Python 3에서 list.index (x) 오류 처리

  22. 22

    Having trouble getting calls to addChild() on nested children in vanilla ActionScript 3 to do anything

  23. 23

    Python 3 print ([1, 2] 및 3) 출력 3

  24. 24

    Getting correct perf version

  25. 25

    String of list or strings to a tuple

  26. 26

    Python Convert set to list, keep getting TypeError: 'list' object is not callable

  27. 27

    ValueError: list.remove(x): x not in list python

  28. 28

    The effect of position in comparing an object with a null reference

  29. 29

    Comparing two files to print a line that matches a word

뜨겁다태그

보관