如何在Python中导航数组?

时间:2016-03-23 15:05:34

标签: python arrays

我试图创建一个代码,当用户输入y / n时,用户将转到数组中的下一个条目。当它们到达数组的末尾时,用户将返回到数组的开头,依此类推。到目前为止这是我的代码。我对此进行了很多研究,但仍然不知道该怎么做。     为了清楚起见,我需要在循环数组时需要帮助,同时还允许用户输入选择在哪里做。

#declaring array names.
longitude=[]; latitude=[]; messagetext=[];encryptions=[];
input_file = open('messages.txt', 'r')


lines_in_file_array = input_file.read().splitlines()


#appending the lines in a select file to select records.
for line in lines_in_file_array:
     record_array = line.split(',')
     longitude.append(record_array[0])
     latitude.append(record_array[1])
     messagetext.append(record_array[2])

input_file.close()

def encrypt():
    temporary_array=[]
    for index in range(len(messagetext)):
        x=messagetext[index]
        x=([ord(character)+2 for character in x])
        codedx=''.join([chr(character) for character in x])
        temporary_array.append(codedx)
        print(codedx)

def navigation():
    continues=False
    while continues == True:




encrypt()
print(messagetext)

3 个答案:

答案 0 :(得分:0)

要获取用户条目,请使用input(),如下所示:

answer = input("See next entry ? (y/n)" )
if answer == "y":
    #do the stuff

您可以使用itertools.cycle来循环输入,这样:

from itertools import cycle

lines_in_file_array = input_file.read().splitlines()

lines_in_file_array = cycle(lines_in_file_array)

...

然后,你可以无限循环:

for line in lines_in_file_array:
    ....

然后返回数组的开头直到结束

答案 1 :(得分:0)

我不确定您要导航哪个数组,但要使用用户输入进行导航:

def navigation():
    i = 0
    continues = True
    user = input("Continue?y/n")
    if user == "y":
        while continues:
             print array[i]
             i = (i+1)%len(array)
             user = input("Continue?y/n")
             if user != "y":
                 continues = False

答案 2 :(得分:0)

一旦你有了数组,只需几行代码即可完成。

# Index counter
i = 0;

# Loop forever
while True:

    # Get the user's input, and store the response in answer
    answer = input("See next entry (y/n)? ")

    # If the user entered "y" or "Y"
    if answer.lower() == "y":

        # print the message
        print(messagetext[i % len(messagetext)])

        # and increment the index counter
        i = i + 1

    # Otherwise leave the loop
    else:
        break