首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用Python访问list中的子组

如何用Python访问list中的子组
EN

Stack Overflow用户
提问于 2022-07-27 15:53:06
回答 1查看 70关注 0票数 -3

我有一个包含子组的列表。我根据基金名称的相似性进行了分组。如何选择/识别列表中的组?

代码语言:javascript
运行
复制
mylist = [
    {'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}
    {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}, 
    {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]

例如,如何调用/选择第二组:{'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}

我的最终目标是在每一组中只保留一只基金,这是最好的股票类别,但首先,我需要一种方法来识别每个分组。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-27 16:19:21

您可以对列表索引进行切片或插入:

代码语言:javascript
运行
复制
mylist = [{'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}, {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}, {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]

MFSC = mylist[1]
print(MFSC)

输出:

代码语言:javascript
运行
复制
{'MFS Conservative Allocation R2', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R4', 'MFS Conservative Allocation R6'}

但是list的元素是一个集合,所以set元素可以在每次使用它们时以不同的顺序出现,并且不能被索引或键引用。

代码语言:javascript
运行
复制
MFSC = list(mylist[1])
print(MFSC)

输出:

代码语言:javascript
运行
复制
['MFS Conservative Allocation R4', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73141067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档