Список не перезаписывается ожидаемым образом - PullRequest
0 голосов
/ 18 июня 2019

Я новичок в Python. Мой код должен сделать это проверить строку по существующему списку, если строка еще не находится в файле местоположения, он просит пользователя назначить ему значение и обновляет проверяемый список. против. Я проверил, что списки правильно читают текстовые файлы (в следующем формате).

Результат, который он дает мне, является бесконечным циклом, потому что он не находит строку в списке, даже после того, как он был добавлен. Я ожидаю, что он сломается после того, как пользователь введет 'n', а затем какое-нибудь строковое значение

(Также будет дополнительная строка для if dummyvar in location:, но я еще не дошел до этого.)

Переменные

 from_location = [ company, address, city, state ] #changes line by line
 location = [[ 'company a', 'address a', 'city a', 'state a', 'classification a'],
             [ 'company b', 'address b', 'city b', 'state b', 'classification b']]
 loc_opt = ['classification a', 'classification b', 'classification c']

Фрагмент кода:

        while from_location not in location[:][0:-1]:
                ftext=("This location has not been indexed. Please enter the " +
                      "location name or input one of these prompts \n" + 
                      " 'l' to list all acceptable locations\n" + 
                      " 'n' to add a new location\n" +
                      " 'p' to print the full line of information\n" +
                      "Company:   " +  str(from_location[0]) + " \n" +
                      "Address:   " + str(from_location[1]) + "\n" +
                      "City:   " + str(from_location[2]) + "\n" +
                      "State:   " + str(from_location[3]) + "\n")

                dummyvar = input(ftext)
                if dummyvar == "l":
                    print("Current Location Options are:  \n ")
                    for item in loc_opt:
                        print("  ", item ,"  ")
                if dummyvar == "p":
                    print("Entire Line :  ", spline,"\n")
                if dummyvar == "n":
                    new_location=input("Please input new location:\n")
                    new_location.upper()
                    new_location = [new_location]
                    loc_opt = loc_opt + new_location
                    location = location + [from_location + new_location]
                    print(location) 

Полный код

print("Press Ctrl C with the Python window selected \n"
      "at any time to stop the program. A loud beep "
      "will sound \n when the program is finished.\n\n")
date = 00000000
counter = 1
dummyvar="q"

ref_fp =(r"filepath")
loc_opt_fn = open(ref_fp + "LOCATION OPTIONS.txt")
loc_ref_fn = open(ref_fp + "LOCATION REFERENCE.txt")

loc_opt = loc_opt_fn.read().split("\n")


location = loc_ref_fn.read().split("\n")

for index in range(len(location)):
    location[index]=location[index].split("\t")

while len(str(date))!= 8 or (date < 20180101 or date > 20301231):
    date = input("What date is the file would you like to clean"
             "( yyyymmdd year like: 20190227). \n\n")
    date = str(date).strip()
    try:
        date = int(date)
    except:
        print("\nNo letters please!\n")
        date = 000

fp1 = (r"anotherfilepath")
fp2 = ( r" filename.txt")

fpr= (r"yetanotherfilepath")
filepath = fp1 + str(date) + fp2

with open(filepath) as source:
    for line in source:
        line.strip("\n")
        spline = line.split("\t")
        if counter == 1:
            spline.append("FROM")
            spline.append("TO")
        else:
            spline.append("")
            spline.append("")
        if spline[0] == "NC":
            #So we've added two columns, FROM and To
            #And we are only operating on the lines that are NC
            #Because that excludes the exceptions.
            #Now we want to check and see if the From and
            #To information is in the reference lists.
            from_location=[spline[5],spline[7],spline[9],spline[10]]
            to_location=[spline[13],spline[15],spline[17],spline[18]]

            while from_location not in location[:][0:-1]:
                    ftext=("This location has not been indexed. Please enter the " +
                          "location name or input one of these prompts \n" + 
                          " 'l' to list all acceptable locations\n" + 
                          " 'n' to add a new location\n" +
                          " 'p' to print the full line of information\n" +
                          "Company:   " +  str(from_location[0]) + " \n" +
                          "Address:   " + str(from_location[1]) + "\n" +
                          "City:   " + str(from_location[2]) + "\n" +
                          "State:   " + str(from_location[3]) + "\n")

                    dummyvar = input(ftext)
                    if dummyvar == "l":
                        print("Current Location Options are:  \n ")
                        for item in loc_opt:
                            print("  ", item ,"  ")
                    if dummyvar == "p":
                        print("Entire Line :  ", spline,"\n")
                    if dummyvar == "n":
                        new_location=input("Please input new location:\n")
                        new_location.upper()
                        new_location = [new_location]
                        loc_opt = loc_opt + new_location
                        location = location + [from_location + new_location]
                        print(location)

    counter += 1 
import winsound
winsound.Beep(600,500)
print("\n\n\n----------------------------Processing is finished.----------------------------\n\n\n") 

1 Ответ

1 голос
/ 19 июня 2019

location[:][0:-1] не удаляет последний элемент из каждого элемента location.Это эквивалентно temp = location[:], за которым следует temp[0:-1].temp является просто копией location, а затем возвращает список со всеми элементами, кроме последнего.

Вы можете делать все, что хотите, с пониманием списка:

while from_location not in [l[0:-1] for l in location]:
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...