Как работают циклы «внутри» внутри 2D-списка? - PullRequest
0 голосов
/ 09 марта 2019

Итак, в основном я нашел код, который может импортировать CSV-файл в 2D-список, но я не могу понять, как циклы «for» работают внутри списка.То же самое относится и к циклу for внутри оператора if.

Вот мой код:

def dataRead():
    with open("Inventory_List.csv", "r") as my_csv:
        myFile = csv.reader(my_csv, delimiter=",")

        global dataInventoryList
        dataInventoryList = [[col[0], col[1], col[2], col[3], col[4], eval(col[5])] for col in myFile]

Так что я могу эффективно применить это понимание к моей будущей манипуляции со списком ис умом.


Полный код:

def dataRead():
    with open("Inventory_List.csv", "r") as my_csv:
        myFile = csv.reader(my_csv, delimiter=",")

        global dataInventoryList
        dataInventoryList = [[col[0], col[1], col[2], col[3], eval(col[4]), eval(col[5])] for col in myFile]


def dataWrite():
    with open("Inventory_List.csv", "w+") as my_csv:
        myFile = csv.writer(my_csv, delimiter=',', lineterminator='\n')
        myFile.writerows(dataInventoryList)

def main():
    while True:
        found = False
        dataRead()
        print("==========================================================================")
        print("Before update;")

        for i in range(len(dataInventoryList)):
            for j in range(6):
                print(str(dataInventoryList[i][j]) + "\t", end="")
            print("")

        search = input("Enter product code: ")
        quantity = int(input("Please enter quantity: "))
        choice = int(input("Add stocks[1] Pull Stacks[2]\nChoice: "))

        for i in range(len(dataInventoryList)):
            if search == dataInventoryList[i][0]:
                found = True
                if choice == 1:
                    dataInventoryList[i][5] += quantity
                    break
                elif choice == 2:
                    if dataInventoryList[i][5] == 0:
                        print("Requested order is out of stocks!\n")
                        break
                    elif quantity > dataInventoryList[i][5]:
                        print("Requested order is out of range!\n")
                        break
                    elif quantity <= dataInventoryList[i][5]:
                        dataInventoryList[i][5] -= quantity
                        break

        if found == False:
            print("Requested order was not found on the database!\n")

        elif found == True:
            dataWrite()

        print("After update;")
        for i in range(len(dataInventoryList)):
            for j in range(6):
                print(str(dataInventoryList[i][j]) + "\t", end="")
            print("")

main()

~Inventory_List.csv
CS001,Pieces,Hardie Flex,Construction Materials,5,100
CS002,Pieces,Hammer,Construction Materials,4,100
CS003,Pieces,Mallet,Construction Materials,7,100

Ответы [ 2 ]

0 голосов
/ 09 марта 2019

Прежде чем посмотреть на код, Поймите, как структурирован CSV:

  • Файл CSV имеет минимум 6 столбцов
  • В столбцах с 0 по 4 содержатся случайные данные, а в столбце 5 - математические выражения

Схематически говоря:

   |  0  |  1  |  2  |  3  |  4  |  5  |  - - -
---+-----+-----+-----+-----+-----+-----+
 0 | d00 | d01 | d02 | d03 | d04 | e05 |  - - -
 1 | d10 | d11 | d12 | d13 | d14 | e15 |  - - -
 2 | d20 | d21 | d22 | d23 | d24 | e25 |  - - -
 . |  .  |  .  |  .  |  .  |  .  |  .  |
 . |  .  |  .  |  .  |  .  |  .  |  .  |
 . |  .  |  .  |  .  |  .  |  .  |  .  |

Вот что делает код:

  1. Файл CSV открывается в режиме чтения
  2. Глобальный список dataInventoryList создается для хранения данных в CSV
  3. Цикл for перебирает строки в файле CSV
  4. Данные в текущей строке принимаются как list
  5. Оператор eval() решает математические выражения в этой строке и добавляет результат к предыдущему list
  6. list добавляется к dataInventoryList

Результат dataInventoryList будет:

[[d00, d01, d02, d03, d04, r05]
 [d00, d01, d02, d03, d04, r05]
 [d00, d01, d02, d03, d04, r05]
 .
 .
 .                             ]

, где rAB представляет результат, полученный при решении eAB


Более простой для понимания эквивалент for цикла в вашем коде:

dataInventoryList = []

for aRow in myFile:
     rowList = [ aRow[0] , aRow[1] , aRow[2] , aRow[3] , aRow[4] ]
     rowList.append( eval(aRow[5]) )

     dataInventoryList.append( rowList )

Надеюсь, это поможет ..!

0 голосов
/ 09 марта 2019

Ваш код содержит список понимания Вы можете прорваться простым циклом for и добавить данные столбца в массив

def dataRead():
    with open("Inventory_Lists.csv", "r") as my_csv:
      myFile = csv.reader(my_csv, delimiter=",")
      global dataInventoryList
      dataInventoryList =[]

      for col in myFile:
         dataInventoryList.append([col[0], col[1], col[2], col[3], col[4]])
      print(dataInventoryList )

Простой синтаксис понимания списка имя переменной = [(данные для итерации цикла) (для цикла)]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...