用Python进行列表操作

2024-09-30 22:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的JSON文件,包含文章的标题和主体,如下所示。你知道吗

{
    "paragraphs": [
        "Ismael Omar Guelleh, known in Djibouti by his initials, IOG, won a second term in a one-man presidential race in 2005 and a third term in April 2011.", 
        "Parliament - which does not include any representatives of the opposition - approved an amendment to the constitution in 2010 allowing the president to run for a third term.", 
        "The constitutional reforms also cut the presidential mandate to five years from six, and created a senate.", 
        "Mr Guelleh succeeded his uncle and Djibouti's first president, Hassan Gouled Aptidon, in April 1999 at the age of 52. He was elected in a multi-party ballot.", 
        "Mr Guelleh supports Djibouti's traditionally strong ties with France and has tried to reconcile the different factions in neighbouring Somalia."
    ], 
    "description": "A profile of Djibouti's political leader, President Guelleh", 
    "title": "Djibouti profile"
},

我想做的是,每当我把一个标题和它对应的段落附加到一个列表中时,我想包括那些有四个或更多段落的标题(例如,我上面发布的例子有5个,所以我想包括它)。我尝试打印段落长度:

print len(y['paragraphs']

它可以工作,但我不能用它来控制将要附加的内容。你知道吗

我在Python中使用以下代码:

titles = []
vocabulary = []
paragraphs = []

with open("/Users/.../file.json") as j:
data = json.load(j)


for x in range(0,len(data)):
    titles.append(data[x]['title'])
    paragraphs.append(data[x]['paragraphs'])

for y in range(3000, 3500):
   # here I believe there must be an if statement
    vocabulary.append(titles[y])
    vocabulary.append(paragraphs[y][0])
    vocabulary.append(paragraphs[y+1][0])

我尝试在第二个后面添加if语句,例如:

if len(y['paragraphs']) > 4:

我有个错误: TypeError:“int”对象没有属性“getitem

我知道解决方案是一个简单的一行代码,但我卡住了。有什么想法吗?你知道吗

谢谢!你知道吗


Tags: andofthetoin标题fordata
2条回答

for循环中定义y

for y in range(3000, 3500):

这意味着y将采用30003001。。。3499。这些都是int的值。因此,下面这行试图在一个明显不存在的int上使用dict查找(.getitem)。你知道吗

if len(y['paragraphs']) > 4:

我们需要的是:

for y in range(3000, 3500):
    length = len(paragraphs[y])
    if length > 4:
    ...

相关问题 更多 >