簡體   English   中英

輸入驗證並將元組列表轉換為 txt 文件

[英]Input validation and converting list of tuples to txt file

我試圖將元組列表轉換為 txt 文件並對兩個輸入進行輸入驗證。 順便說一句,我試圖在沒有 CSV 模塊的情況下做到這一點。 我得到了這個元組列表:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]

我想將它轉換為一個看起來像這樣的 txt 文件:

Age      Name     YOB
16       Peter    2005
21       Philip   2000
10       Kate     2011

我需要進行輸入驗證,以確認第一個輸入是一個列表,第二個輸入是一個字符串。 文件行應該用制表符分隔。

def my_func(list1,new_file):
   header = "Age, Name, YOB"
   if isinstance(list1, list):
      for i in list1:
        if isinstance(list1[i], str):
            with open("Age_file.txt", "w") as output:
                output.write(header + "\n")
                output.close()
                with open("Age_file.txt", "w") as output:
                    for i in output:
                        output.write(str(i) + "\n")
        else:
            "Second input must be a str."
else:
    "First input must be a list."

但我得到這個類型錯誤:

'''
if isinstance(list1[i], str):
TypeError: list indices must be integers or slices, not tuple
'''

感謝任何形式的幫助,謝謝!

這里的問題是您的第二個for循環中的i是您的回溯中描述的tuple 您本質上是在嘗試執行以下錯誤:

list1[(16, 'Peter' , 2005)]

聽起來您想確保每個元組的第二項是str ,在這種情況下,您的代碼應該如下所示。 我還對其進行了修改,以便您只打開文件一次,而不是在每次迭代時繼續使用您似乎根本沒有使用的new_file參數。

def my_func(list1, new_file):
    if not isinstance(list1, list):
        raise ValueError("First argument must be a list!")
    header = "Age, Name, YOB"
    with open(new_file, "w") as output:
        output.write(header + "\n")
        for line in list1:
            if not isinstance(line[1], str):
                raise ValueError("Second item in each tuple must be a str!")
            
            vals = ",".join(str(i) for i in line)
            output.write(vals + "\n")

您是否嘗試過創建三個單獨的列表而不是元組? 那么你只有一個字符串列表和兩個數字列表......然后你可以輸入:

list1 = [16, 21, 10]
list2 = ['Peter', 'Philipp', 'Kate']
list3 = [2005, 2000, 2010]
listfull = list(zip(list1, list2, list3))

然后你可以從這些列表中制作一個 dataframe :

df = pd.DataFrame(listfull, columns =['Age', 'Name', 'YOB'])

然后您可以將其保存為文本或 csv 文件...不確定是否有幫助..

df.to_csv('df.csv')

下面的評論中提到了您的代碼失敗的原因:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here

def my_func(list1,new_file):
    #assuming we are getting same list1 defined above list1 is still list of tuples
    header = "Age, Name, YOB"
    if isinstance(list1, list):
        for i in list1:
            # i should be tuples like (16, 'Peter' , 2005)
            if isinstance(list1[i], str): # error thrown because i is tuple
                with open("Age_file.txt", "w") as output:
                    output.write(header + "\n")
                    output.close()
                    with open("Age_file.txt", "w") as output:
                        for i in output:
                            output.write(str(i) + "\n")
            else:
                "Second input must be a str."
    else:
        "First input must be a list."
        

你可以試試下面的代碼:

list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here


def my_func(list1,new_file):
    if not isinstance(list1, list):
        raise Exception("list1 must be a list") # exception thrown in case list1 is not a list
    if not isinstance(new_file, str):
        raise Exception("new_file must be a str") # exception thrown in case new file is not a str.
        # However in your code it is not clear what is the purpose of argument new_file
    result = "Age\tName\tYOB\n" # \t for tab. tab is better than space is it somewhat maintains indentation of the columns
    for list2 in list1:
        result += "\t".join([str(x) for x in list2]) + "\n"
        # list comprehension used to convert all item in tuple list2 to strings
    with open("Age_file.txt", "w") as output:
        output.write(result.strip())


my_func(list1, "test")

暫無
暫無

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

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