如何替换2D列表中的多个项目?

时间:2017-12-12 19:08:31

标签: python list nested-lists

我需要一个只包含逗号分隔的字符串的列表。我不知道如何在python中做到这一点。

以下是我的示例输入:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ListView lView;
ArrayList<String> devNameList, devAddressList;

private ListAdapter arrayAdapter;
private ConnectThread mConnectThread;
private BluetoothSocket mmSocket = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final static int REQUEST_ID = 2;

// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String devName = device.getName();
            String devAddress = device.getAddress();

            devAddressList.add(devAddress);

            if (devName == null){
                devName = device.getAddress();
            }

            devNameList.add(devName);

            lView.setAdapter(arrayAdapter);
        }
    }
};

private class ConnectThread extends Thread {
    ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;

        try {
            // Get a BluetoothSocket to connect with the given BluetoothDevice.
            // MY_UUID is the app's UUID string, also used in the server code.
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "ERROR: Socket's create() method failed", Toast.LENGTH_SHORT).show();
        }
        mmSocket = tmp;
    }

    public void run() {
        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and return.
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                Toast.makeText(getBaseContext(), "ERROR: Could not close the client socket",
                        Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // The connection attempt succeeded. Perform work associated with
        // the connection in a separate thread.
        manageMyConnectedSocket();
    }

    // Closes the client socket and causes the thread to finish.
    void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "ERROR: Could not close the client socket",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_new_device);

    requestPermissions();

    lView = findViewById(R.id.discList);

    devNameList = new ArrayList<>();
    devAddressList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, devNameList);

    if (mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
    }
    // Register for broadcasts when a device is discovered.
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    mBluetoothAdapter.startDiscovery();

    lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String devName = devNameList.get(position);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if((Objects.equals(devName, "HC-06"))|| (Objects.equals(devName, "00:21:13:00:97:6A"))){
                    Toast.makeText(AddNewDevice.this, "Please wait...", Toast.LENGTH_SHORT).show();

                    mBluetoothAdapter.cancelDiscovery();

                    String address = devAddressList.get(position);
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    mConnectThread = new ConnectThread(device);
                    mConnectThread.run();
                }
                else{
                    Toast.makeText(AddNewDevice.this, "Please connect to an HC-06 device.", Toast.LENGTH_SHORT).show();
                }
            }
            else {
                if("HC-06".equals(devName) || "00:21:13:00:97:6A".equals(devName)){
                Toast.makeText(AddNewDevice.this, "Please wait...", Toast.LENGTH_SHORT).show();

                mBluetoothAdapter.cancelDiscovery();

                String address = devAddressList.get(position);
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                mConnectThread = new ConnectThread(device);
                mConnectThread.run();
                }
                else{
                    Toast.makeText(AddNewDevice.this, "Please connect to an HC-06 device.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

private void requestPermissions(){
    int androidVersion = Build.VERSION.SDK_INT;
    if (androidVersion >= 23){
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                }, REQUEST_ID);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
    mBluetoothAdapter.cancelDiscovery();
}

private void manageMyConnectedSocket() {
    mConnectThread.cancel();
    finish();
}

我的预期输出是:

[(0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'), (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.253*"shall" + 0.241*"people" + 0.236*"unto" + 0.196*"indeed" + 0.131*"upon" + 0.118*"come" + 0.109*"thou"'), (2, '-0.682*"lord" + 0.497*"shall" + 0.349*"unto" + 0.125*"thou" + 0.125*"thee" + -0.098*"indeed" + 0.092*"come" + -0.092*"said" + 0.092*"people" + 0.080*"truth"')]

2 个答案:

答案 0 :(得分:2)

您可以尝试正则表达式:

  

一线解决方案:

import re
pattern = r'[a-z]+'

string_1 = [(0,'0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"')]
print([k if isinstance(k, int) else [i.group() for i in re.finditer(pattern, str(string_1))] for i in string_1 for k in i])

输出:

[0, ['allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth']]
  

详细解决方案:

final_list=[]
for i in string_1:
    for k in i:
        if isinstance(k,int):
            final_list.append(k)
        else:
            for i in re.finditer(pattern, str(string_1)):
                final_list.append(i.group())

print(final_list)

正则表达式解释:

**[a-z]**
Match a single character present in the list below [a-z]+
**+ Quantifier** — 
Matches between one and unlimited times, as many times as possible, 
giving back as needed (greedy)
  

根据您的要求编辑回答:

import re
pattern = r'[a-z]+'

string_1 = [(0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'), (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.253*"shall" + 0.241*"people" + 0.236*"unto" + 0.196*"indeed" + 0.131*"upon" + 0.118*"come" + 0.109*"thou"'), (2, '-0.682*"lord" + 0.497*"shall" + 0.349*"unto" + 0.125*"thou" + 0.125*"thee" + -0.098*"indeed" + 0.092*"come" + -0.092*"said" + 0.092*"people" + 0.080*"truth"')]
print([k if isinstance(k, int) else [i.group() for i in re.finditer(pattern, str(i))] for i in string_1 for k in i])

输出:

[0, ['allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth'], 1, ['lord', 'said', 'allah', 'shall', 'people', 'unto', 'indeed', 'upon', 'come', 'thou'], 2, ['lord', 'shall', 'unto', 'thou', 'thee', 'indeed', 'come', 'said', 'people', 'truth']]

如果您想要更具体的结果,那么您可以尝试:

print([[k if isinstance(k, int) else tuple([i.group() for i in re.finditer(pattern, str(k))]) for k in i] for i in string_1])

输出:

[[0, ('allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth')], [1, ('lord', 'said', 'allah', 'shall', 'people', 'unto', 'indeed', 'upon', 'come', 'thou')], [2, ('lord', 'shall', 'unto', 'thou', 'thee', 'indeed', 'come', 'said', 'people', 'truth')]]

答案 1 :(得分:0)

转换的关键是挑选双引号中的单词。为此,我会使用正则表达式。我的解决方案看起来像这样:

from pprint import pprint
import re

def transform(t):
    return (t[0],) + tuple(re.findall(r'"(\w+)"', t[1]))

inlist = [
    (0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'),
    (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.253*"shall" + 0.241*"people" + 0.236*"unto" + 0.196*"indeed" + 0.131*"upon" + 0.118*"come" + 0.109*"thou"'),
    (2, '-0.682*"lord" + 0.497*"shall" + 0.349*"unto" + 0.125*"thou" + 0.125*"thee" + -0.098*"indeed" + 0.092*"come" + -0.092*"said" + 0.092*"people" + 0.080*"truth"'),
]

outlist = map(transform, inlist)
pprint(outlist)

输出:

[(0, 'allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth'),
 (1, 'lord', 'said', 'allah', 'shall', 'people', 'unto', 'indeed', 'upon', 'come', 'thou'),
 (2, 'lord', 'shall', 'unto', 'thou', 'thee', 'indeed', 'come', 'said', 'people', 'truth')]