我输入的内容会有所不同。
data = [(("101","A"),5), (("105","C"),12), (("101", "B"),4)]
寻找按键[0]分组的输出,保留键[1]的所有项目。并且,对这些值求和。
output = [(("101", "A", "B"),9), (("105", "C"),12)]
我已经尝试过了。
my_dict = dict(data)
final_values = {}
for k,v in my_dict.items():
key1 = k[0]
key2 = k[1]
if key1 not in final_values:
final_values[key1] = []
final_values[key1].append(key2)
final_values[key1].append(v)
哪个回来。
{'101': ['A', 5, 'B', 4], '105': ['C', 12]}
我想获取列表中数字的总和。
答案 0 :(得分:3)
while True:
container = driver.find_elements_by_xpath('.//*[contains(@class,"review-container")]')
for items in container:
element = WebDriverWait(driver, 1000).until(EC.element_to_be_clickable((By.XPATH,'.//*[contains(@class,"taLnk ulBlueLinks")]')))
element.click()
time.sleep(10)
contained = items.find_elements_by_xpath('.//*[contains(@class,"ui_column is-9")]')
for item in contained:
try:
driver.execute_script("[...document.querySelectorAll('.mgrRspnInLine')].map(el => el.parentNode.removeChild(el))")
rating = item.find_element_by_xpath('//*[contains(@class,"ui_bubble_rating bubble_")]')
rate = rating .get_attribute("class")
rate = str(rate)
rate = rate[-2:]
score_list.append(rate)
time.sleep(2)
stay = item.find_element_by_xpath('.//*[contains(@class,"recommend-titleInline")]')
stayed = stay.text
stayed = stayed.split(', ')
stayed.append(stayed[0])
travel_type.append(stayed[1])
WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH,'.//*[contains(@class,"noQuotes")]')))
summary = item.find_element_by_xpath('.//*[contains(@class,"noQuotes")]')
comment = summary.text
comments.append(comment)
WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH,'.//*[contains(@class,"ratingDate")]')))
rating_date = item.find_element_by_xpath('.//*[contains(@class,"ratingDate")]')
date = rating_date.get_attribute("title")
date = str(date)
review_date.append(date)
WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH,'.//*[contains(@class,"partial_entry")]')))
review = item.find_element_by_css_selector(".partial_entry")
comment = review.text
print(comment)
except (NoSuchElementException) as e:
continue
try:
element = WebDriverWait(driver, 100).until(EC.element_to_be_clickable((By.XPATH,'.//*[contains(@class,"nav next taLnk ui_button primary")]')))
element.click()
time.sleep(2)
except (ElementClickInterceptedException,NoSuchElementException) as e:
print(e)
break
答案 1 :(得分:0)
您可以尝试使用collections.defaultdict()
对项目进行分组,然后在末尾将结果展平:
from collections import defaultdict
from operator import itemgetter
data = [(("101","A"),5), (("105","C"),12), (("101", "B"),4)]
d = defaultdict(list)
for (x, y), z in data:
d[x].append((y, z))
result = [
((k, *tuple(map(itemgetter(0), v))), sum(map(itemgetter(1), v)))
for k, v in d.items()
]
print(result)
# [(('101', 'A', 'B'), 9), (('105', 'C'), 12)]