我有以下格式的列表:
[('car crash killed', 95), ('car accident crash', 86), ('disaster police car', 45)]
我想提取具有最大数字的字符串/句子并将其打印在文本文件中。在这种情况下,输出将是:
car crash killed
如果有两个或多个具有相同最大数字的字符串/句子,我想将它们全部提取出来。例如:
[('car crash killed', 95), ('car accident crash', 95), ('disaster police car', 45)]
输出:
car crash killed
car accident crash
如何提取?
答案 0 :(得分:2)
使用max
获得具有最大价值的物品:
lst = [('car crash killed', 95), ('car accident crash', 86), ('disaster police car', 45)]
print(max(lst, key=lambda x: x[1])[0])
# car crash killed
现在,要返回所有最大值项目,基本上应用相同的逻辑。获取max_value
并使用如下列表理解返回带有max_value
的所有项目:
lst = [('car crash killed', 95), ('car accident crash', 95), ('disaster police car', 45)]
max_value = max(lst, key=lambda x: x[1])[1]
print([x[0] for x in lst if x[1] == max_value])
# ['car crash killed', 'car accident crash']
答案 1 :(得分:0)
from collections import Counter
dictionary = dict([('car crash killed', 95), ('car accident crash', 95), ('disaster police car', 45)])
counter = Counter(dictionary)
max_value = counter.most_common(1)[0][1]
print(max_value)
result = list(string for string, count in counter.most_common() if count == max_value)
print(result)
答案 2 :(得分:0)
给出具有重复值的列表(96):
case R.id.child2 :
ImageView url = (ImageView) view;
String urls;
urls = cursor.getString(cursor.getColumnIndex(Database.DATABASE_CHILD_2));
Glide.with(Nostrils.this).load(urls).apply(noTransformation()).into(url);
url.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(Nostrils.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_custom_layout, null);
PhotoView photoView = mView.findViewById(R.id.imageView);
photoView.setImageDrawable(((ImageView)view).getDrawable());
mBuilder.setView(mView);
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
});
break;
然后按值对它进行排序,然后选择最高的值:
data = [('car crash killed', 95),
('car accident crash', 86),
('disaster police car', 45),
('road', 95)]
这可以通过列表理解来简化:
data = sorted([(y, x) for x, y in data], reverse=True)
out = []
highest = data[0][0]
for y, x in data:
if y == highest:
out.append(x)
print(out)
['road', 'car crash killed']