簡體   English   中英

Python 循環列出打印索引或數組

[英]Python Loop to List Print Index or Array

下午好,Python 新手在這里。 我正在嘗試返回從文本文件中抓取的客戶信息列表。 我需要 output 采用名稱、帳號、日期格式。 我最初的想法是,

抓取數據創建列表按 index_number 打印,例如(姓名 1、帳號 1、日期 1)

不幸的是,這不起作用,因為列表將打印出所有名稱,然后是所有帳號,然后是日期。 我需要將列表打印為姓名、帳號、日期。

我很確定這是因為我運行循環的方式。 下面是我一直在處理的代碼。

   import re

fin = open(destFileLoc,"r")
text = fin.read()


nameMatch = re.findall(r'\n\w+\s+\w+\s\w+', text)
# for i in range(len(nameMatch)):
#     name = nameMatch # print("Name: " + nameMatch[i])

acctMatch = re.findall(r'\s{4}\d{8}', text)
# for i in range(len(acctMatch)):
#     account = acctMatch  ##print("Account Num: " + acctMatch[i])

dateMatch = re.findall(r'(\d+/\d+/\d+)', text)
# for i in range(len(dateMatch)):
#     date = dateMatch  ## print("Date of Service : " + dateMatch[i])

patList = [[nameMatch], [acctMatch], [dateMatch]]
for i in range(patList):
    print("====== Name     Account Number       Date ======\n" + str(nameMatch[i]), str(acctMatch[i]), str(dateMatch[i]))

您可以嘗試使用結合了多個列表的 zip

for name, acctNum, date in zip(nameMatch, acctMatch, dateMatch):
    print(str(name), str(acctNum), str(date))

嘗試...

另見format模塊

nameMatch =["Smith", "Jones", "Thompson"]
acctMatch =["12345", "54321", "22333"]
dateMatch =["2019-10-1", "2019-10-2", "2019-10-3"]

a = list(zip(
    nameMatch,
    acctMatch, 
    dateMatch
))

print(a)

for _list in a:
    print("=========================")
    print("Printing the list itself: ", _list)
    print ('Printing the items in _list:', _list[0], _list[1], _list[2])

print("=========================")
print ('Printing the items with format and columns:')
for _list in a:
    print( '{0:.<10}{1:.<10}{2:.<10}'.format(_list[0], _list[1], _list[2]))

OUTPUT:

[('Smith', '12345', '2019-10-1'), ('Jones', '54321', '2019-10-2'), ('Thompson', '22333', '2019-10-3')]
=========================
Printing the list itself:  ('Smith', '12345', '2019-10-1')
Printing the items in _list: Smith 12345 2019-10-1
=========================
Printing the list itself:  ('Jones', '54321', '2019-10-2')
Printing the items in _list: Jones 54321 2019-10-2
=========================
Printing the list itself:  ('Thompson', '22333', '2019-10-3')
Printing the items in _list: Thompson 22333 2019-10-3
=========================
Printing the items with format and columns:
Smith.....12345.....2019-10-1.
Jones.....54321.....2019-10-2.
Thompson..22333.....2019-10-3.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM