Как применить функцию к последовательности диктов? - PullRequest
0 голосов
/ 28 ноября 2018

У меня есть следующая функция:

def count_chars(e):
    return len(e)

Я выполняю json следующим образом:

In:

a_lis = []
with open('../JSON_FILE.json','r') as fa:
    a = json.load(fa)
    for e in a['entries']:
        pprint(e)

Out:

{'data': ['string'], 'type': 'one'}
{'data': ['a string '], 'type': 'one'}
{'data': ['another string'], 'type': 'three'}
...
{'data': ['one more string'], 'type': 'two'}

Как применить функцию count_chars и добавить ее или обновить как новую строку в списке 'data'?Например, ожидаемый результат будет выглядеть следующим образом:

{'data': ['string','6'], 'type': 'one'}
{'data': ['a string','8'], 'type': 'one'}
{'data': ['another string','14'], 'type': 'three'}
...
{'data': ['one more string','15'], 'type': 'two'}

ОБНОВЛЕНИЕ :

Я обнаружил, что мои списки содержат более одного элемента, например: ['first', 'second string']?Как я могу вернуть ['first', len_1, 'second string', len_2]

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Это должно работать:)

def count_chars(e):
    return len(e)

a_lis = []
with open('../JSON_FILE.json','r') as fa:
    a = json.load(fa)
    for e in a['entries']:
        for String in e["data"]: # Grab one string inside the strings list.
            if type(String) == int:
                continue # Skip the count chars value that you appended.
            Length = count_chars(String) # Apply the function.
            e["data"].append(Length) # Append the returned value to the data list containing the string.

        # Now we reorder the list from ["a", "ab", "abc", 1, 2, 3] to ["a", 1, "ab", 2, "abc", 3]
        strings_found = int(len(e["data"])/2)
        reordered_list = []

        for start in range(0, strings):
            reordered_list = reordered_list + [x for x in e["data"][start::strings_found ]]
        e["data"] = reordered_list
0 голосов
/ 28 ноября 2018

Вы можете использовать append():

lst = [
    {"data": ["string"], "type": "one"},
    {"data": ["a string "], "type": "one"},
    {"data": ["another string"], "type": "three"},
]

def count_chars(e):
    return len(e)

for d in lst:
    d["data"].append(count_chars(d["data"][0]))

print(lst)
# [{'data': ['string', 6], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]

Если в списке больше строк, вы можете использовать extend() и перестроить новый список:

lst = [
    {"data": ["string", "hi"], "type": "one"},
    {"data": ["a string "], "type": "one"},
    {"data": ["another string"], "type": "three"},
]

def count_chars(e):
    return len(e)

for d in lst:
    newlst = []
    for x in d["data"]:
        newlst.extend([x, count_chars(x)])
    d["data"] = newlst

print(lst)
# [{'data': ['string', 6, 'hi', 2], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]

Примечание: Поскольку count_chars() просто возвращает len(), может быть проще просто вызвать len().

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