簡體   English   中英

帶有true和false的python列表不是True和False

[英]python list with true and false not True and False

- - - - - - - - - - - - 更新 - - - - - - - - - - -

由於存在太多混亂,我決定給出更詳細的解釋。 看看下面的代碼,並專注於

day = {"days": buildString2(day_array[i])}

這是代碼:

import csv, sys, requests, json, os, itertools, ast

def buildString(item):
    item_array = item.split(",")
    mod = []
    for i in range(len(item_array)):
        mod.append("%s" % item_array[i].strip())
    return mod

def buildString2(item):
    item_array = item.split(",")
    mod = "["
    for i in range(len(item_array)):
        if i == len(item_array) - 1:
            mod = mod + '%s' % item_array[i].strip()
        else:
            mod = mod + '%s, ' % item_array[i].strip()
    mod = mod + "]"
    return mod

if __name__ == '__main__':
    def main():
        filename = 'file.csv'
        dict = {"id":'c8d5185667f'}

        with open(filename, 'r', encoding='utf8') as f:
            reader = csv.reader(f)
            try:
                count = 0
                for row in reader:
                    count = count + 1
                    if count != 1:

                        dict["name"] = row[10]

                        dict["space_usages"] = buildString(row[19])

                        availablle_array = []
                        available_booking_hours = row[15]
                        days = row[18]
                        availability_array = available_booking_hours.split("*")
                        day_array = days.split("*")
                        for i in range(len(day_array)):
                            startEndTime = availability_array[i].split("-")
                            day = {"days": buildString2(day_array[i])}
                            times = {"start_time":startEndTime[0], "end_time":startEndTime[1]}
                            day["times"] = times
                            availablle_array.append(day)

                        dict["available_days"] = availablle_array

                        print(dict)
                        url = 'http://50.97.247.68:9000/api/v1/spaces'
                        response = requests.post(url, data=json.dumps(dict))

當我打印字典時,得到以下內容

{'id': 'c8d5185667f', 'available_days': [{'days': '[true, true, true, true, true, true, true]', 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}

但是我老板要這個

{'id': 'c8d5185667f', 'available_days': [{'days': [true, true, true, true, true, true, true], 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}

這也不起作用

{'id': 'c8d5185667f', 'available_days': [{'days': ['true', 'true', 'true', 'true', 'true', 'true', 'true'], 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}

這更有意義嗎? 有可能得到

[true, true, true, true, true, true, true]

作為價值? 我嘗試這樣做

day = {"days": ast.literal_eval(buildString2(day_array[i]))}

但它崩潰了。 我沒主意了。 我嘗試使用Google搜索各種內容,但似乎找不到任何東西。 非常感謝您的幫助。 老實說,我不相信這是可能的,但這就是我被告知要做的。

注意:它們必須為小寫。 這不行

[True, True, True, True, True, True, True]

這是JSON,因此您應該將一周轉換為JSON格式

In [1]: import simplejson as json
In [2]: week = [True, False, True, True]
In [3]: json.dumps(week)
Out[3]: '[true, false, true, true]'

要轉換回去,只需加載並解析它:

In [8]: print json.loads('[true, false, false, true]')
[True, False, False, True]

您可以使用json模塊將布爾值列表轉換為字符串並相互轉換:

>>> import json
>>> json.dumps([True, False, True, True, False])
'[true, false, true, true, false]'
>>> json.loads('[true, false, true, true, false]')
[True, False, True, True, False]

你的價值是

week = '[true, false, true, false, true, false, true]'

這是JSON表示形式。 第二個值是

week = ['true', 'false', 'true', 'false', 'true', 'false', 'true']

這是帶有“ true”和“ false”字符串的列表。

week = [True, False, True, False, True, False, True]

這是純python代碼。

您必須決定要擁有的值以及選擇以哪種方式將其轉換為哪種形式的值。

對於第一個值,您可以使用json.loads

對於第二個值,您必須手動檢查字符串“ true”和“ false”

第三是僅python,因此無需再次在python中進行更改:)。

這有可能讓你的老板想什么,只是不使用內置的真假:

class MyBool(object):
    def __init__(self, value):
        self.value = bool(value)
    def __repr__(self):
        return repr(self.value).lower()
    def __bool__(self):
        return self.value

print({'a' : [MyBool(True), MyBool(True), MyBool(False)]})

結果:

{'a': [true, true, false]}

您實際上並不需要__bool__ ,但是(在Python 3中)它允許在邏輯條件下使用對象。

因此,根據要求,它不是有效的Python文字,因為它使用true而不是True ,並且它不是有效的JSON,因為它使用單引號的字符串而不是雙引號。 大概是由不接受True且不接受雙引號字符串的內容解析的嗎? 我不認為有可能僅修復原始API來接受JSON嗎?

暫無
暫無

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

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