Python常见问题

Python常见问题,第1张

Python常见问题

1.(格式化)空列表延展后,直接返回结果会换行:解决办法return print()

比如:

from typing import List
SAMPLE_DATA_1 = [[0, 1, ['NDP', 'LIBERAL', 'GREEN', 'CPC'], [1, 4, 2, 3],
                  [False, True, False, False]],
                 [1, 2, ['LIBERAL', 'NDP', 'GREEN', 'CPC'], [2, 1, 4, 2],
                  [False, False, True, True]],
                 [1, 3, ['GREEN', 'NDP', 'CPC', 'LIBERAL'], [1, 5, 1, 2],
                  [False, True, False, True]],
                 [1, 4, ['CPC', 'LIBERAL', 'NDP', 'GREEN'], [5, 0, 3, 2],
                  [True, False, True, True]]]
def get_votes_in_riding(vote_data: List['VoteData'], riding: int
                        ) -> List['VoteData']:
    list_get_votes_in_riding = []
    for l in vote_data:
        if l[0] == riding:
            list_get_votes_in_riding.append(l)
    return list_get_votes_in_riding         
get_votes_in_riding(SAMPLE_DATA_1, 0)

返回

Out[7]: 
[[0,
  1,
  ['NDP', 'LIBERAL', 'GREEN', 'CPC'],
  [1, 4, 2, 3],
  [False, True, False, False]]]

加一个print()

from typing import List
SAMPLE_DATA_1 = [[0, 1, ['NDP', 'LIBERAL', 'GREEN', 'CPC'], [1, 4, 2, 3],
                  [False, True, False, False]],
                 [1, 2, ['LIBERAL', 'NDP', 'GREEN', 'CPC'], [2, 1, 4, 2],
                  [False, False, True, True]],
                 [1, 3, ['GREEN', 'NDP', 'CPC', 'LIBERAL'], [1, 5, 1, 2],
                  [False, True, False, True]],
                 [1, 4, ['CPC', 'LIBERAL', 'NDP', 'GREEN'], [5, 0, 3, 2],
                  [True, False, True, True]]]
def get_votes_in_riding(vote_data: List['VoteData'], riding: int
                        ) -> List['VoteData']:
    list_get_votes_in_riding = []
    for l in vote_data:
        if l[0] == riding:
            list_get_votes_in_riding.append(l)
    return print(list_get_votes_in_riding)      #print()格式化         
get_votes_in_riding(SAMPLE_DATA_1, 0)

返回

[[0, 1, ['NDP', 'LIBERAL', 'GREEN', 'CPC'], [1, 4, 2, 3], [False, True, False, False]]]

2.(特殊类型)字符串类型list转换成list

https://cloud.tencent.com/developer/article/1453964https://cloud.tencent.com/developer/article/1453964

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5479461.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存