检查字典中的唯一值并返回列表

时间:2015-08-09 12:06:25

标签: python list dictionary

我一直在努力练习这个练习几天,我发现每个近似都有一个新问题,想法是在字典上找到那些独特的值,并返回一个带有键的列表

例如: 如果public class TerritorySpinnerDisplayAdapter extends BaseAdapter { private Context mContext; private ArrayList<String> territoryName; private ArrayList<String> territoryId ; public TerritorySpinnerDisplayAdapter(Context c,ArrayList<String> territoryName,ArrayList<String> territoryId) { // TODO Auto-generated constructor stub this.mContext = c; this.territoryName = territoryName; this.territoryId = territoryId; } @Override public int getCount() { // TODO Auto-generated method stub return territoryName.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int pos, View child, ViewGroup parent) { // TODO Auto-generated method stub Holder mHolder; LayoutInflater layoutInflater; if (child == null) { mHolder = new Holder(); layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); child = layoutInflater.inflate(R.layout.list_territory_dialog_block,null); mHolder.territoryNameView = (TextView) child.findViewById(R.id.dialog_block_territory_name); mHolder.territoryIdView = (TextView) child.findViewById(R.id.dialog_block_territory_id); child.setTag(mHolder); }else { mHolder = (Holder) child.getTag(); } mHolder = (Holder) child.getTag(); if(pos < territoryName.size() && mHolder.territoryNameView!=null ){ String name = territoryName.get(pos); mHolder.territoryNameView.setText(name); } if(pos < territoryId.size() && mHolder.territoryIdView!=null ){ String bid = territoryId.get(pos); mHolder.territoryIdView.setText(bid); } //Log.d("@@@@@@@@@@@@@@@@@@@@@@@@Testing@@@@@@@@@@@@@@@@@@@@",blockName.get(0) + blockId.get(0) + territoryId.get(0)); return child; } public class Holder { TextView territoryNameView; TextView territoryIdView; } } ,那么您的函数应该返回final Dialog dialog = new Dialog(getActivity()); dialog.setContentView(R.layout.list_view); dialog.setTitle("Select City"); ListView listView = (ListView) dialog.findViewById(R.id.list); dialog.show(); territoryAdapter = newTerritorySpinnerDisplayAdapter(getActivity(), arrTerr, arrTerr1); listView.setAdapter(territoryAdapter); territoryAdapter.notifyDataSetChanged(); ,因为值1,2和4只出现一次。

这是我到目前为止所尝试的:

aDictionary  = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}

如果我这样做,我可以指出并删除大于1的那些,但问题仍然存在,我将有一个零,我不希望它在原始列表中不是唯一的。

[1, 3, 8]

我尝试用这种方式用整数来检查哪些是第一次出现,但不能将它翻译成字典或继续从这里开始。此外,我不确定是否允许在答案中导入模块,并且必须是没有外部模块的方法。

def existsOnce(aDict):

counting = {}
tempList = []

for k in aDict.keys():
    print k,
    print aDict[k]


print 'values are:'
for v in aDict.values():
    print v,
    counting[v] = counting.get(v,0)+1
    print counting[v]
    tempNumbers = counting[v]
    tempList.append(tempNumbers)
print tempList

从这里我无法以任何理由取值并比较它们,我试图用以下语句提取值:

def existsOnce2(aDict):

# import Counter module in the top with `from collections import Counter`

c = Counter()

for letter in 'here is a sample of english text':
    c[letter] += 1
    if c[letter] == 1:
        print c[letter],':',letter

但是我做错了什么,无法访问这些值。

3 个答案:

答案 0 :(得分:3)

你只需要使用你的<div id="hubs"> <h3>Nos Hubs</h3> <hr> <a class="thumbnail vignette-hub" href="http://kkw.fr"> <img style="opacity: 0.6;filter: alpha(opacity=60);" alt="Aéroport de Nantes" src="http://kkw.fr/uploads/upload-center/nantes-vue-aerienne091501270208.png" width="100%" /> <p class="txt-hub-image"> Hub de</br>Nantes </p> </a> </div> dict并保持vals中的密钥值为aDict的值,然后调用sorted来获取排序的输出列表:

count == 1

使用collections.Counter dict进行计数只需在你的值上调用Counter然后应用相同的逻辑,只需保持每个具有v count == 1的k来自Counter dict:

def existsOnce3(aDict):  
    vals = {}
    # create dict to sum all value counts
    for i in aDict.values():
        vals.setdefault(i,0)
        vals[i] += 1   
    # use each v/val from aDict as the key to vals
    # keeping each k/key from aDict if the count is 1
    return sorted(k for k, v in aDict.items() if vals[v] == 1)

答案 1 :(得分:1)

这个怎么样:

func processImage(image: UIImage, colors: Int) -> UIImage{
    var img1:CIImage = CIImage(image: image)!
    img1 = img1.imageByApplyingFilter("CIPhotoEffectMono", withInputParameters:["inputImage" : img1])
    img1 = img1.imageByApplyingFilter("CISharpenLuminance", withInputParameters: ["inputImage" : img1])
    img1 = img1.imageByApplyingFilter("CIColorPosterize", withInputParameters: ["inputImage" : img1, "inputLevels" : colors])
    img1 = img1.imageByApplyingFilter("CIColorControls", withInputParameters: ["inputImage" : img1, "inputSaturation" : 1, "inputBrightness": 0.2, "inputContrast": 1.5 //8
        ])
    img1 = img1.imageByApplyingFilter("CIHighlightShadowAdjust", withInputParameters: ["inputImage" : img1, "inputHighlightAmount": 6, "inputShadowAmount": 0])
    img1 = img1.imageByApplyingFilter("CIColorPosterize", withInputParameters: ["inputImage" : img1, "inputLevels" : 3])

    let uiImg = UIImage(CIImage: img1)
    print("x")
    return uiImg ?? UIImage()
}

结果:

from collections import Counter

my_dict  = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}

val_counter = Counter(my_dict.itervalues())
my_list = [k for k, v in my_dict.iteritems() if val_counter[v] == 1]

print my_list

答案 2 :(得分:0)

一个班轮:

>>> aDictionary  = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}
>>> unique_values = [k for k,v in aDictionary.items() if list(aDictionary.values()).count(v)==1]
>>> unique_values
[1, 3, 8]