附加到python列表

时间:2016-09-16 15:46:17

标签: python list

我有一个网络剪贴簿,它返回我的值,如下例所示。

# Other code above here.
test = []

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")

    for each_item in product_feature.find_elements_by_tag_name('img'):
        zz = test.append(each_item.get_attribute('src')[34:-4])  # returning the values I want
        print(zz)

上面的代码会打印出这样的结果:(这是我想要的值)

TCP_active
CI
DOH_active
TCP_active
CI
DOH
TCP
CI_active
DOH_active

我想达到以下结果:

[TCP_active, CI, DOH_active]
[TCP_active, CI, DOH]
[TCP, CI_active, DOH_active]

我应该怎么做?

我试过了:

test.append(each_item.get_attribute('src')[34:-4])

但是这给了我:

[TCP_active]
[TCP_active, CI]
[TCP_active, CI, DOH_active]
[TCP_active, CI, DOH_active, TCP]
...

希望我的解释清楚

2 个答案:

答案 0 :(得分:2)

而不是print,将结果附加到列表中;每次迭代外循环一个新列表:

test = []

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")
    features = [] 
    for each_item in product_feature.find_elements_by_tag_name('img'):
        features.append(each_item.get_attribute('src')[34:-4])
    test.append(features)

如果您愿意,可以打印features,或test,只是为了查看for循环的每个级别发生的情况。

答案 1 :(得分:0)

好的,不确定你想要什么,但下面的代码将给出你想要的输出:

test = []

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")

    zz = []
    for each_item in product_feature.find_elements_by_tag_name('img'):
        zz = test.append(each_item.get_attribute('src')[34:-4])  # returning the values I want

    print(zz)

如果您想存储数据而不打印数据,请使用以下字典:

test = []
zz_store = {}

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")

    zz = []
    for each_item in product_feature.find_elements_by_tag_name('img'):
        zz = test.append(each_item.get_attribute('src')[34:-4])  # returning the values I want

    zz_store[result] = zz
    print(zz)