列出单词匹配给定前缀的新单词列表(python理解问题)

时间:2018-10-01 05:15:38

标签: python list dictionary list-comprehension prefix

我需要一些帮助才能在python中提出以下问题。 1.称为starts_with(prefix,wordlist)的函数,它以字符串前缀和字符串wordlist列表作为输入,并使用列表推导返回一个列表,该列表包含wordlist中所有以前缀开头的单词。

我所做的是

def starts_with (prefix, wordlist):
    if prefix == wordlist[0][:len(prefix)]:
    return [wordlist[0]]+ starts_with(prefix,wordlist[1:])

我刚刚发现这既不是错误也不是理解。我不知道该如何理解。

3 个答案:

答案 0 :(得分:0)

您可以像这样使用列表理解:

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();


//this context we will use to inflate the layout
    //Remove this..Please
    // CheckBox checkBox;

    //private Context mCtx;
    private SearchableSpinner spinner;

    //we are storing all the products in a list
    private List<Product> productList;

    private Activity create;

    public ProductAdapter(Activity activity) {
        create = activity;
    }


    //getting the context and product list with constructor
    public ProductAdapter(Activity activity, List<Product> productList) {
        // this.mCtx = mCtx;
        create = activity;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(create);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProductViewHolder holder, final int position) {
        // //getting the product of the specified position


        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
                Product.getSpinnerItemsList());
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.spinner.setAdapter(spinnerArrayAdapter);

        holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
                mSpinnerSelectedItem.put(position, mPosition);

                TextView mTextView = view.findViewById(R.id.mSpinnerText);
           /* Toast.makeText(create, "Selected Item: " + mTextView.getText().toString(), Toast.LENGTH_LONG).show();
            Log.e("***************", "Selected Item: " + mTextView.getText().toString());*/


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //binding the data with the viewholder views
        if (mSpinnerSelectedItem.containsKey(position)) {
            holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
        }


        holder.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);


                // set title
                alertDialogBuilder.setTitle("Delete Item");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Are you sure you want to delete this item?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity

                                productList.remove(position);
                                notifyItemRemoved(position);

                                Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();


                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });





    }


    @Override
    public int getItemCount() {
        return productList.size();
    }


    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View rootView;


        public ProductViewHolder(View itemView) {
            super(itemView);

            spinner = itemView.findViewById(R.id.spinner);
            editText = itemView.findViewById(R.id.editText);
            textView5 = itemView.findViewById(R.id.textView5);
            checkBox = itemView.findViewById(R.id.checkBox);
            rootView = itemView.findViewById(R.id.linearLayout);


            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // makes the set disappear when checkbox is ticked.
                    if(isChecked){

                        productList.remove(getAdapterPosition());
                        notifyItemRemoved(getAdapterPosition());



                        Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
                    }

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }

}

答案 1 :(得分:0)

filter

def starts_with(prefix, wordlist):
    return list(filter(lambda x: x.startswith(prefix),wordlist))

答案 2 :(得分:0)

def starts_with(prefix, wordlist):
        wordswithPrefixList =[]
        for word in wordlist:
            if word.startswith(prefix):
                wordswithPrefixList.append(word)

        return wordswithPrefixList
print(starts_with("test", ["test2","test1","sfsdf"]))