对数据进行排序并打印到文件中

时间:2016-05-25 04:15:58

标签: python file sorting

我有五个功能i)实验室平均值ii)program_average iii)midterm_average iv)final和v)weighted_total_score

如何创建一个新功能,根据上述其中一个选项对数据进行排序,并将其写入用户选择的文件中?

到目前为止,我的代码相当重复。有没有办法可以浓缩这个?

def sorted_data(student_name):

    print("This option is for sorting students data and printing in a file")
    print("(i) lab average, (ii) program average, (iii) midterm average, (iv) final, (v) weighted total score")
    user_sorted_data=(input("Select one of the options (i-v):"))
    write_sorted_file=print(input("What file would you like this written into?"))

    if (user_sorted_data=='i'):
        print("You have selected sorting student data upon lab average")
        f=open('write_sorted_file','w')
        f.write (str(student_lab_average(student_scores)))
        f.close()

    if (user_sorted_data=='ii'):
        print("You have selected sorting student data upon program average")
        f=open('write_sorted_file','w')
        f.write (str(student_prog_average(student_scores)))
        f.close()

    if (user_sorted_data=='iii'):
        print("You have selected sorting student data upon midterm average")
        f=open('write_sorted_file','w')
        f.write (str(mid_average(student_scores)))
        f.close()

    if (user_sorted_data=='iv'):
        print("You have selected sorting student data upon the final grade")
        f=open('write_sorted_file','w')
        f.write (str(overall_grade(student_scores)))
        f.close()

    if (user_sorted_data=='v'):
        print("You have selected sorting student data upon weighted total score")
        f=open('write_sorted_file','w')
        f.write (str(weighted_total_score(student_scores)))
        f.close()

我正在调用这样的函数

elif(ch== 'e'):
    print(" ")
    student_name=input("Type the student's last name:")
    print(" ")
    scores= get_data_for_student(student_name,mid1,mid2,final,homework,labs,program1,program2,program3,participation)
    f=open('write_sorted_file', 'w')
    print(" ")
    f.write("Here are all the numbers in the text file sorted.") +    str(sorted_data(scores))
    f.close()

3 个答案:

答案 0 :(得分:4)

这是我可以缩小的小,

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RichEditText editPara_et=(RichEditText )findViewById(R.id.editPara);
    String htmlString="<p>I have an Edit Text with html String.</p>";
    editPara_et.setText(Html.fromHtml("<p>I have an Edit Text with html String.</p>"));
    MyTextWatcher TW1 = new MyTextWatcher(editPara_et,MainActivity.this,htmlString);
    editPara_et.addTextChangedListener(TW1);
}
class MyTextWatcher implements TextWatcher {
    public EditText editText;
    Context context;
    //constructor
    public MyTextWatcher(EditText et,Context ctx,String scriptWithParaTags){
        super();
        editText = et;
        context=ctx;
    }
    //Some manipulation with text
    public void afterTextChanged(Editable s) {

    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after){
        Log.e("TC", "beforeTC "+ s.subSequence(start, start + count).toString());
    }

    public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        int cursorIndex=start+1; // This Index is worng as I need index with html Tags

        /* Eg:- Stirng str= <p> I have an EditText with html String </p> 
        * If I place cursor after 'I' cursor position should be 6 if cursorIndex start with 1. but I am getting 2 
        * 
        * */

    }

}

编辑:

变量名称不相同。

在定义要传递分数的函数时,您使用options_functions = {'i':student_lab_average, 'ii':student_prog_average, 'iii':overall_grade, 'iv': overall_grade, 'v':weighted_total_score } options_strings = {'i':'lab average', 'ii':'program average', 'iii':'midterm average', 'iv': 'final grade', 'v':'weighted total score' } def sorted_data(student_scores): print("This option is for sorting students data and printing in a file") print("(i) lab average, (ii) program average, (iii) midterm average, (iv) final, (v) weighted total score") user_sorted_data=input("Select one of the options (i-v):") write_sorted_file=input("What file would you like this written into?") print("You have selected sorting student data upon "+options_strings[user_sorted_data]) f=open('write_sorted_file','w') f.write(str(options_functions[user_sorted_data](student_scores))) f.close() 作为局部变量名。将其更改为“student_scores”。

student_name变量不存在于全局或本地,因此其引发错误student_scores未定义

此行存在错误

student_scores

函数f.write("Here are all the numbers in the text file sorted.") + str(sorted_data(scores))没有返回任何内容。它返回sorted_data

你不能添加函数和字符串

None放在f.write("Here are all the numbers in the text file sorted.")内,当您写入sorted_data中的文件或将其打开为sorted_data时,如果您将其打开为append,它将替换所有以前的数据

答案 1 :(得分:1)

Python列表有一个内置的list.sort()方法,可以就地修改列表。还有一个sorted()内置函数,它从迭代构建一个新的排序列表。因此,假设每个方法(lab_average,prog_average等)返回一个整数列表,您可以通过调用sort()并仅打开和关闭文件一次非常容易地压缩它。

 with open('write_sorted_file','w') as f:

    if (user_sorted_data=='i'):

        print("You have selected sorting student data upon lab average")
        arr_of_int = student_lab_average(student_scores)
        f.write (str(arr_of_int.sort()))

    #other if statements

    f.close()

答案 2 :(得分:0)

我看到你的代码中重复了以下几行:

print("You have selected sorting student data upon lab average")



f=open('write_sorted_file','w')

f.write (str(student_lab_average(student_scores)))

f.close()

您可以将这些行包装成如下所示的函数

def writeToSortedFile(sortFunction, message)
    print(message)

    f=open('write_sorted_file','w')

    f.write (str(sortedFunction(student_scores)))

    f.close()

上面的代码只是删除了代码重复。您可以在每个writeToSortedFile语句后致电if