Python:为每个对象添加多个值

2024-05-14 09:08:28 发布

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

使用Selenium+Python时,我正在尝试使用多个值以在foreach循环中发送,到目前为止,我能够发送到值,但是如果插入,语法看起来不正确:

lists = {
      'name1' : 'surname1'
      'name2' : 'surname2'
      'name2' : 'surname2'
}

我需要通过foreach传递给Selenium的是这样的数据:

lists = {
      'name1' : 'surname1' : 'age1' : 'location1'
      'name2' : 'surname2' : 'age2' : 'location2'
      'name2' : 'surname2' : 'age3' : 'location3'
}

我肯定我的语法有问题,有什么帮助吗?你知道吗


Tags: 数据selenium语法listsforeachname1name2age2
2条回答

如果需要将多个值集分组以在for循环中使用,可以尝试

lists = [['name1', 'surname1', 'age1', 'location1'],
         ['name2', 'surname2', 'age2', 'location2'],
         ['name3', 'surname3', 'age3', 'location3']]

然后迭代为

for item in lists:
    name = item[0]
    surname = item[1]
    age = item[2]
    location = item[3]
    # do something with all those values

或者(最好):

for name, surname, age, location in lists:
    # do something with all those values

如果surnameagelocation是具有name的人的属性/属性,那么您可以通过将人name作为dictionary key来实现这一点,并将所有其他属性作为list来实现,如下所示

lists = { 
    name1 : [surname1 , age1, location1],
 } 

然后你可以迭代列表如下-

for key,value in lists: 
    # do something with key 
    for surname,age,location in value: 
        # do something with surname,key,location

相关问题 更多 >

    热门问题